该注解顾名思义加强器,对注解了Controller类的加强,@ControllerAdvice的实现:app
/** * Specialization of {@link Component @Component} for classes that declare * {@link ExceptionHandler @ExceptionHandler}, {@link InitBinder @InitBinder}, or * {@link ModelAttribute @ModelAttribute} methods to be shared across * multiple {@code @Controller} classes. * * performance and add complexity. * * @author Rossen Stoyanchev * @author Brian Clozel * @author Sam Brannen * @since 3.2 */ @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @Documented @Component public @interface ControllerAdvice {
部分源码,该注解使用@Component注解,这样的话当咱们使用<context:component-scan>扫描时也能扫描到。看注释@link意思即把@ControllerAdvice注解内部使用@ExceptionHandler、@InitBinder、@ModelAttribute注解的方法应用到全部的 @RequestMapping注解的方法。spa
1.@ExceptionHandler(异常类)这个注解则表示Controller中任何一个方法发生异常,则会被注解了@ExceptionHandler的方法拦截到。对应的异常类执行对应的方法,若是都没有匹配到异常类,则采用近亲匹配的方式。debug
2.@ModelAttribute有三个做用code
①绑定请求参数到命令对象:放在功能处理方法的入参上时,用于将多个请求参数绑定到一个命令对象,从而简化绑定流程,并且自动暴露为模型数据用于视图页面展现时使用;component
②暴露表单引用对象为模型数据:放在处理器的通常方法(非功能处理方法)上时,是为表单准备要展现的表单引用对象,如注册时须要选择的所在城市等,并且在执行功能处理方法(@RequestMapping注解的方法)以前,自动添加到模型对象中,用于视图页面展现时使用;orm
③暴露@RequestMapping方法返回值为模型数据:放在功能处理方法的返回值上时,是暴露功能处理方法的返回值为模型数据,用于视图页面展现时使用。对象
@ControllerAdvice public class CurrentUserControllerAdvice { private static final Logger log = LoggerFactory.getLogger(CurrentUserControllerAdvice.class); @ModelAttribute("currentUser") public CurrentUser getCurrentUser(Authentication auth, HttpServletRequest request, HttpServletResponse response) throws Exception { CurrentUser user = (auth == null) ? null : (CurrentUser) auth.getPrincipal(); log.debug("CurrentUser={}, URL={}", user, request.getRequestURL()); if (user != null) { log.debug("Username={}, Role={}", user.getUsername(), user.getRole()); } return user; } }
这段代码的意思则为把返回的user对象设置到Model中,对于以后的RequestMapping的方法调用能够直接取获得对应key值currentUser的value值。对于一个用户认证明现能够使用这个注解。blog