淺談對ControllerAdvice註解的理解

  該註解顧名思義加強器,對註解了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

相關文章
相關標籤/搜索