Spring中的@ControllerAdvice注解的使用

今天在CodeReview的时候,看到李明同学的代码中用了ControllerAdvice这个注解,觉得挺有用的,就搜集了一下他的用法;

@ControllerAdvice,是Spring3.2引入的新注解,意为增强型控制器;

@ControllerAdvice注解内部使用@ExceptionHandler、@InitBinder、@ModelAttribute注解的方法应用到所有的 @RequestMapping注解的方法。

网上的一个例子,我搬过来:

    @ControllerAdvice  
    public class ControllerAdviceTest {  
      
        @ModelAttribute  
        public User newUser() {  
            System.out.println("============应用到所有@RequestMapping注解方法,在其执行之前把返回值放入Model");  
            return new User();  
        }  
      
        @InitBinder  
        public void initBinder(WebDataBinder binder) {  
            System.out.println("============应用到所有@RequestMapping注解方法,在其执行之前初始化数据绑定器");  
        }  
      
        @ExceptionHandler(UnauthenticatedException.class)  
        @ResponseStatus(HttpStatus.UNAUTHORIZED)  
        public String processUnauthenticatedException(NativeWebRequest request, UnauthenticatedException e) {  
            System.out.println("===========应用到所有@RequestMapping注解的方法,在其抛出UnauthenticatedException异常时执行");  
            return "viewName"; //返回一个逻辑视图名  
        }  
    }  


评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值