1. 引入依赖
<!--configuration-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
注意:若返回响应结果的实体类未用到lombok相关注解可不加lombok依赖
2. 创建一个返回响应结果的实体类
public class Result {
private Integer code;//响应码,0 代表成功; 1 代表失败
private String msg; //响应信息 描述字符串
private Object data; //返回的数据
//增删改 成功响应
public static Result success(){
return new Result(0,"success",null);
}
//查询 成功响应
public static Result success(Object data){
return new Result(0,"success",data);
}
//失败响应
public static Result error(String msg){
return new Result(1,msg,null);
}
}
2. 创建全局响应结果处理程序拦截响应结果并封装
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.lang.NonNull;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;
@RestControllerAdvice
public class WrapperResponseBodyAdvice implements ResponseBodyAdvice<Object> {
@Override
public boolean supports(MethodParameter returnType, @NonNull Class<? extends HttpMessageConverter<?>> converterType) {
return returnType.getParameterType() != Result.class;
}
@Override
public Object beforeBodyWrite(
Object body, @NonNull MethodParameter returnType, @NonNull MediaType selectedContentType,
@NonNull Class<? extends HttpMessageConverter<?>> selectedConverterType,
@NonNull ServerHttpRequest request, @NonNull ServerHttpResponse response) {
// 根据路径判断该结果是否封装
if (request.getURI().getPath().equals("/doc.html")) {
return body;
}
// 若响应结果为空,封装结果
if (body == null) {
return Result.success();
}
// 根据响应结果类型判断该结果是否封装
if (body instanceof Result) {
return body;
}
return Result.success(body);
}
}
3. 将全局响应结果处理程序添加到Spring容器中
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import javax.servlet.Filter;
@ConditionalOnClass({Filter.class})
@Configuration
public class MvcConfig implements WebMvcConfigurer {
@Bean
public WrapperResponseBodyAdvice wrapperResponseBodyAdvice() {
return new WrapperResponseBodyAdvice();
}
}
4. 将MvcConfig类实现自动配置
方式一:在 resources 目录下创建 META-INF/spring.factories
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.demo.config.MvcConfig
方式二: 在 resources 目录下创建 META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports
com.demo.config.MvcConfig