假设有个场景,每一个 controller 都需要接收一个共同的参数,那么除了在每一个方法中都加入这个参数之外,还有一个方法就是使用@ControllerAdvice 注解。
@ControllerAdvice 参数之前的文章(http://www.javathings.top/springboot 中异常处理/)提到过,用于全局的处理异常。
@ControllerAdvice 和@ModelAttribute 注解配合使用,可以实现全局的 Controller 都接收到同一个 Model。举个例子:
package com.xxx.utils;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestParam;
@ControllerAdvice("com.xxx.restful")
public class MyControllerAdvice {
@ModelAttribute
public void processParam(@RequestParam String param) {
System.out.println("param="+param);
}
}
MyControllerAdvice 这个类中的 processParam 方法,就实现了处理统一的 param 参数(controller 必须是在 com.xxx.restful 包中的)。
这能大大简化代码的书写,非常有用。
具体是实现和细节,还是自己手动的实现一下,加深印象。
ControllerAdvice 注解的详细文档,参考官方地址:
https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/bind/annotation/ControllerAdvice.html
原创文章,转载请注明出处!http://www.javathings.top/场景:当所有的controller,都需要传入某个参数,代码如/
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有