SpringBoot中@ControllerAdvice注解简介说明

欣喜 SpringBoot 发布时间:2024-04-28 17:28:24 阅读数:8930 1
下文笔者讲述SpringBoot中@ControllerAdvice注解的简介及说明,如下所示

@ControllerAdvice注解

@ControllerAdvice注解 结合实现RequestBodyAdvice 接口 
    可以拦截所有的@Requestbody注解的内容
例:@ControllerAdvice注解示例
 
@ControllerAdvice(basePackages = "com.java265.xxx.controller")//此处设置需要当前Advice执行的域 , 省略默认全局生效
public class MyEncryptRequestBodyAdvice implements RequestBodyAdvice {
    private Logger log = LoggerFactory.getLogger(this.getClass());
    private boolean encrypt;//业务参数
    @Autowired
    private SecretKeyConfig secretKeyConfig;//业务参数

    public MyEncryptRequestBodyAdvice() {
    }
	//第一个执行的方法,该方法判断拦截后是否执行beforeBodyRead()方法;返回false表示不执行
    public boolean supports(MethodParameter methodParameter, Type targetType, Class<? extends HttpMessageConverter<?>> converterType) {
        if (methodParameter.getMethod().isAnnotationPresent(MyDecrypt.class) && !this.secretKeyConfig.isDebug()) {
            this.encrypt = true;
        }

        return this.encrypt;
    }
	//不用关注
    public Object handleEmptyBody(Object body, HttpInputMessage inputMessage, MethodParameter parameter, Type targetType, Class<? 
    extends HttpMessageConverter<?>> converterType) {
        return body;
    }
//业务执行方法,自定义类MyDecryptHttpInputMessage必须实现HttpInputMessage接口,在MyDecryptHttpInputMessage修改请求参数
    public HttpInputMessage beforeBodyRead(HttpInputMessage inputMessage, MethodParameter parameter, Type targetType, Class<? 
     extends HttpMessageConverter<?>> converterType) {
        if (this.encrypt) {
            try {
                HttpInputMessage msg = // message处理
                return msg;
            } catch (Exception var6) {
                this.log.error("Decryption failed", var6);
            }
        }

        return inputMessage;
    }
	//读取参数后执行的代码
    public Object afterBodyRead(Object body, HttpInputMessage inputMessage, MethodParameter parameter, Type targetType,
       Class<? extends HttpMessageConverter<?>> converterType) {
        return body;
    }
}

 
版权声明

本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。

本文链接: https://www.Java265.com/JavaFramework/SpringBoot/202404/8121.html

最近发表

热门文章

好文推荐

Java265.com

https://www.java265.com

站长统计|粤ICP备14097017号-3

Powered By Java265.com信息维护小组

使用手机扫描二维码

关注我们看更多资讯

java爱好者