How to Quickly Bootstrap a Spring Boot Project and Avoid Common Version Pitfalls

This guide walks you through the pain points of environment setup, shows step‑by‑step creation of a Spring Boot project, explains version compatibility between Spring Cloud, Spring Boot and Kafka, and provides ready‑to‑use Maven configurations, global exception handling, logging, CORS, Swagger, and a curated list of useful development tools.

Java Backend Technology
Java Backend Technology
Java Backend Technology
How to Quickly Bootstrap a Spring Boot Project and Avoid Common Version Pitfalls

Project Initialization

If you ask developers what they hate most, most will answer "environment". Setting up the IDE, dealing with licensing, and configuring a new Spring Boot project can be a major headache.

Below is a screenshot of a freshly created Spring Boot project with a main class, configuration file, and a test starter.

Version Management

Spring Cloud and Spring Boot versions must match. See the official compatibility tables: https://spring.io/projects/spring-cloud Spring Boot and Kafka client versions also need to be aligned: https://spring.io/projects/spring-kafka A mismatch (e.g., Kafka server 0.11 with client 3.0.4) can cause errors such as:

Exception thrown when sending a message with key='null' and payload='byte[205]' to topic notify org.apache.kafka.common.errors.UnsupportedVersionException: Attempting to use idempotence with a broker which does not support the required message format (v2). The broker must be version *0.11* or later.

Global Exception Handling

@RestControllerAdvice
@ResponseBody
@Slf4j
public class GlobalExceptionHandler {
    @ExceptionHandler(value = {MethodArgumentNotValidException.class})
    public ResponseResult<String> handleValidException(MethodArgumentNotValidException ex, HttpServletResponse httpServletResponse) {
        log.error("[GlobalExceptionHandler][handleValidException] 参数校验exception", ex);
        return wrapperBindingResult(ex.getBindingResult(), httpServletResponse);
    }

    private ResponseResult<String> wrapperBindingResult(BindingResult bindingResult, HttpServletResponse httpServletResponse) {
        StringBuilder errorMsg = new StringBuilder();
        for (ObjectError error : bindingResult.getAllErrors()) {
            if (error instanceof FieldError) {
                errorMsg.append(((FieldError) error).getField()).append(": ");
            }
            errorMsg.append(error.getDefaultMessage() == null ? "" : error.getDefaultMessage());
        }
        httpServletResponse.setStatus(HttpStatus.BAD_REQUEST.value());
        return ResponseResult.failed(ResultCode.FAILED.getCode(), null);
    }
}

Logging Aspect

@Aspect
@Slf4j
@Component
public class WebLogAspect {
    @Pointcut("@within(org.springframework.stereotype.Controller) || @within(org.springframework.web.bind.annotation.RestController)")
    public void cutController() {}

    @Before("cutController()")
    public void doBefore(JoinPoint point) {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String url = request.getRequestURL().toString();
        List<Object> list = Lists.newArrayList();
        for (Object object : point.getArgs()) {
            if (object instanceof MultipartFile || object instanceof HttpServletRequest || object instanceof HttpServletResponse || object instanceof BindingResult) {
                continue;
            }
            list.add(object);
        }
        log.info("请求 uri:[{}],params:[{}]", url, StringUtils.join(list, ","));
    }

    @AfterReturning(returning = "response", pointcut = "cutController()")
    public void doAfterReturning(Object response) {
        if (response != null) {
            log.info("请求返回result:[{}]", JSONUtil.toJsonStr(response));
        }
    }
}

CORS Configuration

@Configuration
public class GlobalCorsConfig {
    @Bean
    public CorsFilter corsFilter() {
        CorsConfiguration config = new CorsConfiguration();
        config.setAllowedOrigins(Lists.newArrayList("*"));
        config.setAllowCredentials(true);
        config.addAllowedHeader("*");
        config.addAllowedMethod("*");
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", config);
        return new CorsFilter(source);
    }
}

Swagger Configuration

@Configuration
@EnableOpenApi
public class SwaggerConfig {
    @Bean
    public Docket docket() {
        return new Docket(DocumentationType.OAS_30)
                .apiInfo(apiInfo()).enable(true)
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.vines.controller"))
                .paths(PathSelectors.any())
                .build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("项目描述")
                .description("基础服务项目描述")
                .contact(new Contact("作者", "作者URL", "作者Email"))
                .version("1.0")
                .build();
    }
}

Response Wrapper

@Data
public class ResponseResult<T> {
    private int code;
    private String message;
    private T data;

    public static <T> ResponseResult<T> success(T data) {
        ResponseResult<T> r = new ResponseResult<>();
        r.setCode(ResultCode.SUCCESS.getCode());
        r.setMessage(ResultCode.SUCCESS.getMessage());
        r.setData(data);
        return r;
    }

    public static <T> ResponseResult<T> success() {
        ResponseResult<T> r = new ResponseResult<>();
        r.setCode(ResultCode.SUCCESS.getCode());
        r.setMessage(ResultCode.SUCCESS.getMessage());
        return r;
    }

    public static <T> ResponseResult<T> failed(int code, String message) {
        ResponseResult<T> r = new ResponseResult<>();
        r.setCode(code);
        r.setMessage(message);
        return r;
    }

    public static boolean isSucceed(ResponseResult<?> responseResult) {
        return responseResult.getCode() == ResultCode.SUCCESS.getCode();
    }
}

Common Tools

In addition to the basics, the following tools are frequently used in the project:

Embedded Redis: https://github.com/kstyrc/embedded-redis Embedded MariaDB: https://github.com/mariadb Embedded Kafka (Spring Boot starter):

<groupId>org.springframework.kafka</groupId>
<artifactId>spring-kafka</artifactId>

Hutool (Java utility library): https://hutool.cn/ MyBatis‑Plus (ORM framework): https://baomidou.com/ MapStruct (bean mapping): https://mapstruct.org/ Redisson (Redis client):

https://github.com/redisson/redisson

Conclusion

Beyond IDE setup, version mismatches and environment inconsistencies are the real time‑sinks in real‑world development. Understanding how to align Spring Boot, Spring Cloud, and Kafka versions, and leveraging Maven, global exception handling, logging, CORS, and Swagger can dramatically improve productivity.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

JavaException HandlingmavenloggingSpring BootVersion CompatibilitySwagger
Java Backend Technology
Written by

Java Backend Technology

Focus on Java-related technologies: SSM, Spring ecosystem, microservices, MySQL, MyCat, clustering, distributed systems, middleware, Linux, networking, multithreading. Occasionally cover DevOps tools like Jenkins, Nexus, Docker, and ELK. Also share technical insights from time to time, committed to Java full-stack development!

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.