spring boot3单模块项目工程搭建-下(个人开发模板)
    		       		warning:
    		            这篇文章距离上次修改已过425天,其中的内容可能已经有所变动。
    		        
        		                
                在上一篇文章中,我们已经搭建了一个基本的Spring Boot项目框架。在这篇文章中,我们将继续完善这个项目,添加一些常用的配置和工具类。
- 添加全局异常处理器
 
在com.example.demo.exception包下创建GlobalExceptionHandler.java文件,并添加以下代码:
package com.example.demo.exception;
 
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
 
@ControllerAdvice
public class GlobalExceptionHandler {
 
    @ExceptionHandler(Exception.class)
    public ResponseEntity<String> handleException(Exception e) {
        return new ResponseEntity<>("An error occurred: " + e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
    }
}这段代码提供了一个全局异常处理器,能够捕获项目中未处理的异常,并返回一个友好的错误信息。
- 添加Swagger配置
 
在com.example.demo.config包下创建SwaggerConfig.java文件,并添加以下代码:
package com.example.demo.config;
 
import io.swagger.v3.oas.annotations.OpenAPIDefinition;
import io.swagger.v3.oas.annotations.info.Info;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
 
@Configuration
@OpenAPIDefinition(info = @Info(title = "Demo API", version = "0.0.1"))
public class SwaggerConfig {
 
    @Bean
    public Docket api() {
        return new Docket(DocumentationType.OAS_30)
                .select()
                .apis(RequestHandlerSelectors.any())
                .paths(PathSelectors.any())
                .build();
    }
}这段代码配置了Swagger,使得我们可以通过Swagger UI查看和测试API。
- 添加常用工具类
 
在com.example.demo.util包下创建CommonUtils.java文件,并添加以下代码:
package com.example.demo.util;
 
public class CommonUtils {
 
    public static String getCurrentTime() {
        return java.time.LocalDateTime.now().toString();
    }
 
    // 添加其他可能在多个地方使用的工具方法
}这个工具类提供了一个获取当前时间的方法,可以在多处使用,以简化代码和提高复用性。
至此,我们已经为这个Spring Boot项目添加了基本的异常处理、Swagger配置和常用工具类。这为后续的开发提供了一个稳固的基础。
评论已关闭