Master Java Project Setup: From IDE to Spring Boot Scaffolding
This article walks through setting up a Java Spring Boot project, managing compatible Spring Cloud, Spring Boot and Kafka versions, handling common dependency pitfalls with Maven, and provides ready‑to‑use scaffolding code for exception handling, logging, CORS, Swagger, and response wrapping, plus a list of useful development tools.
1. Project Initialization
Developers often complain that setting up the development environment is the most painful part of a project. This guide shows how to quickly create a Spring Boot project using an IDE, including the generated main class, configuration file and test class.
2. Version Management
Before coding, ensure compatibility between Spring Cloud, Spring Boot and Kafka versions. The following links provide official version matrices:
https://spring.io/projects/spring-cloud
https://spring.io/projects/spring-kafka
A common pitfall is using a Kafka client (3.0.4) with a Kafka broker (0.11). The resulting error is:
<code>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.</code>The root cause is mismatched server and client versions; Maven can manage dependencies to avoid such conflicts.
Apache Maven is a project management tool that resolves transitive dependencies. The most frequently used Maven commands are mvn clean install , mvn package , etc.
https://maven.apache.org/index.html
3. Scaffolding – Core Classes
The following essential classes are included in the generated project.
Global Exception Handler
<code>@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);
}
}
</code>Web Log Aspect
<code>@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));
}
}
}
</code>Global CORS Config
<code>@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);
}
}
</code>Swagger Config
<code>@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();
}
}
</code>Response Result Wrapper
<code>@Data
public class ResponseResult<T> {
private int code;
private String message;
private T data;
public static <T> ResponseResult<T> success(T data) {
ResponseResult<T> responseResult = new ResponseResult<>();
responseResult.setCode(ResultCode.SUCCESS.getCode());
responseResult.setMessage(ResultCode.SUCCESS.getMessage());
responseResult.setData(data);
return responseResult;
}
public static <T> ResponseResult<T> success() {
ResponseResult<T> responseResult = new ResponseResult<>();
responseResult.setCode(ResultCode.SUCCESS.getCode());
responseResult.setMessage(ResultCode.SUCCESS.getMessage());
return responseResult;
}
public static <T> ResponseResult<T> failed(int code, String message) {
ResponseResult<T> responseResult = new ResponseResult<>();
responseResult.setCode(code);
responseResult.setMessage(message);
return responseResult;
}
public static boolean isSucceed(ResponseResult responseResult) {
return responseResult.getCode() == ResultCode.SUCCESS.getCode();
}
}
</code>Common Utilities
In addition to the core classes, the following tools are frequently used:
Embedded Redis: https://github.com/kstyrc/embedded-redis
Embedded DB (MariaDB): https://github.com/mariadb
Embedded Kafka (Spring Kafka starter)
Hutool: https://hutool.cn/
MyBatis‑Plus: https://baomidou.com/
MapStruct: https://mapstruct.org/
Redisson: https://github.com/redisson/redisson
Conclusion
While IDE configuration can be tedious, mismatched dependency versions and environment inconsistencies often consume even more time. Proper version management and the use of tools like Maven, embedded services, and well‑structured scaffolding can dramatically improve development efficiency.
Java Tech Enthusiast
Sharing computer programming language knowledge, focusing on Java fundamentals, data structures, related tools, Spring Cloud, IntelliJ IDEA... Book giveaways, red‑packet rewards and other perks await!
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.