99网
您的当前位置:首页SpringBoot实现统一返回接口(除AOP)

SpringBoot实现统一返回接口(除AOP)

来源:99网

起因

关于使用AOP去实现统一返回接口在之前的博客中我们已经实现了,但我突然突发奇想,SpringBoot中异常类的统一返回好像是通过@RestControllerAdvice 这个注解去完成的,那我是否也可以通过这个注解去实现统一返回接口。

正文

这个方法主要是通过@ControllerAdvice + ResponseBodyAdvice实现统一返回结果。其实本质来说和aop实现是相通的明白一个另一个就非常好理解了。
(Result 的代码我就不在这边重复贴了,读者可以去我直接用AOP实现的博客中拿)

import com.study.project.common.BaseResponse;
import com.study.project.common.ResultCode;

import java.lang.annotation.*;

import static com.study.project.common.ResultCode.SUCCESS;

/**
 * @date 2023/2/18
 */
@Documented
@Target({
   ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface FunctionResult {
   
    String value() default "";
    
	//默认code为成功
    ResultCode code() default SUCCESS;
}

自定义一个响应拦截

import com.study.project.annotation.FunctionResult;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.lang.annotation.Annotation;

因篇幅问题不能全部显示,请点此查看更多更全内容