今天在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"; //返回一个逻辑视图名
}
}