Backend Development 12 min read

Project Initialization, Version Management, and Scaffold Setup for Spring Boot Backend Development

This guide walks through initializing a Spring Boot project, handling IDE setup challenges, managing version compatibility between Spring Cloud, Spring Boot, and Kafka, and provides practical code examples for global exception handling, logging, CORS configuration, Swagger integration, and useful development tools.

Java Captain
Java Captain
Java Captain
Project Initialization, Version Management, and Scaffold Setup for Spring Boot Backend Development

1. Project Initialization

If you ask developers what they hate most during development, most will answer "environment, environment, and still environment." Setting up the development environment, especially downloading and configuring an IDE, can be a painful and time‑consuming process.

Modern IDEs are often commercial products, leading many developers to search for cracked versions that require frequent activation or license files. These attempts usually fail and waste valuable time.

People resort to cracked software because they grew up with free tools and find paid software hard to accept, similar to the transition from free MP3 downloads to paid services.

Even though community editions exist (e.g., the free version of JetBrains IDEs), many still struggle with licensing issues, which discourages adoption.

After dealing with the IDE, the next step is to create a Spring Boot project using the IDE’s wizard and click through the prompts.

The newly created project contains a starter class, configuration files, and a test startup class.

2. Version Management

Before diving into development, it’s crucial to understand the compatibility matrix between Spring Cloud, Spring Boot, and Kafka versions.

https://spring.io/projects/spring-cloud

https://spring.io/projects/spring-kafka

A recent incident illustrates the problem: the production Kafka broker was version 0.11, while the client library used by the Spring Boot application was 3.0.4. Although the Spring Boot version matched the Kafka client, the client and broker were incompatible, leading to runtime errors.

?,?: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.

The root cause was the mismatch between production and test environment versions, a common pitfall that Maven can help resolve through dependency management.

Spring Boot’s auto‑configuration simplifies many dependency issues, but conflicts can still arise.

https://maven.apache.org/index.html

Apache Maven is a software project management and comprehension tool

Typical Maven commands such as mvn clean install or mvn package greatly improve development efficiency.

3. No More Talk – Let’s Look at the Scaffold

Below are some core classes used in the project.

@RestControllerAdvice
@ResponseBody
@Slf4j
public class GlobalExceptionHandler {

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

    private ResponseResult
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
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);
    }
}

@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
{
    private int code;
    private String message;
    private T data;

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

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

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

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

3.1 Common Tools

In addition to the basic utilities, the following tools are frequently used in our projects:

Embedded Redis: https://github.com/kstyrc/embedded-redis

Embedded MariaDB: https://github.com/mariadb

Embedded Kafka (Spring Kafka starter): <groupId>org.springframework.kafka</groupId> <artifactId>spring-kafka</artifactId>

Hutool utilities: https://hutool.cn/

MyBatis‑Plus: https://baomidou.com/

MapStruct: https://mapstruct.org/

Redisson: https://github.com/redisson/redisson

Summary

In real work, configuring the IDE is not the most time‑consuming task; a far more frustrating issue is dealing with environment mismatches across development, testing, and production, which can lead to subtle bugs and wasted effort.

Exception HandlingRedisKafkaMavenSpring BootVersion ManagementSwagger
Java Captain
Written by

Java Captain

Focused on Java technologies: SSM, the Spring ecosystem, microservices, MySQL, MyCat, clustering, distributed systems, middleware, Linux, networking, multithreading; occasionally covers DevOps tools like Jenkins, Nexus, Docker, ELK; shares practical tech insights and is dedicated to full‑stack Java development.

0 followers
Reader feedback

How this landed with the community

login 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.