SpringBoot中@ControllerAdvice注解简介说明
下文笔者讲述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; } }
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。