天天看點

Spring3.2新注解@ControllerAdvice

Spring3.2新注解@ControllerAdvice

@ControllerAdvice,是spring3.2提供的新注解,從名字上可以看出大體意思是控制器增強。讓我們先看看@ControllerAdvice的實作:

Java代碼  

Spring3.2新注解@ControllerAdvice
  1. @Target(ElementType.TYPE)  
  2. @Retention(RetentionPolicy.RUNTIME)  
  3. @Documented  
  4. @Component  
  5. public @interface ControllerAdvice {  
  6. }  

 沒什麼特别之處,該注解使用@Component注解,這樣的話當我們使用<context:component-scan>掃描時也能掃描到,

其javadoc定義是:

寫道

即把@ControllerAdvice注解内部使用@ExceptionHandler、@InitBinder、@ModelAttribute注解的方法應用到所有的 @RequestMapping注解的方法。非常簡單,不過隻有當使用@ExceptionHandler最有用,另外兩個用處不大。

接下來看段代碼:

Java代碼  

  1. @ControllerAdvice  
  2. public class ControllerAdviceTest {  
  3.     @ModelAttribute  
  4.     public User newUser() {  
  5.         System.out.println("============應用到所有@RequestMapping注解方法,在其執行之前把傳回值放入Model");  
  6.         return new User();  
  7.     }  
  8.     @InitBinder  
  9.     public void initBinder(WebDataBinder binder) {  
  10.         System.out.println("============應用到所有@RequestMapping注解方法,在其執行之前初始化資料綁定器");  
  11.     }  
  12.     @ExceptionHandler(UnauthenticatedException.class)  
  13.     @ResponseStatus(HttpStatus.UNAUTHORIZED)  
  14.     public String processUnauthenticatedException(NativeWebRequest request, UnauthenticatedException e) {  
  15.         System.out.println("===========應用到所有@RequestMapping注解的方法,在其抛出UnauthenticatedException異常時執行");  
  16.         return "viewName"; //傳回一個邏輯視圖名  
  17.     }  
  18. }  

如果你的spring-mvc配置檔案使用如下方式掃描bean

Java代碼  

Spring3.2新注解@ControllerAdvice
  1. <context:component-scan base-package="com.sishuok.es" use-default-filters="false">  
  2.        <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>  
  3.    </context:component-scan>  

 需要把@ControllerAdvice包含進來,否則不起作用:

Java代碼  

Spring3.2新注解@ControllerAdvice
  1. <context:component-scan base-package="com.sishuok.es" use-default-filters="false">  
  2.        <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>  
  3.        <context:include-filter type="annotation" expression="org.springframework.web.bind.annotation.ControllerAdvice"/>  
  4.    </context:component-scan>  

1、@ModelAttribute注解的方法作用請參考SpringMVC強大的資料綁定(2)——第六章 注解式控制器詳解——跟着開濤學SpringMVC中的【二、暴露表單引用對象為模型資料】,作用是一樣的,隻不過此處是對所有的@RequestMapping注解的方法都起作用。當需要設定全局資料時比較有用。

2、@InitBinder注解的方法作用請參考SpringMVC資料類型轉換——第七章 注解式控制器的資料驗證、類型轉換及格式化——跟着開濤學SpringMVC,同1類似。當需要全局注冊時比較有用。

3、@ExceptionHandler,異常處理器,此注解的作用是當出現其定義的異常時進行處理的方法,其可以使用springmvc提供的資料綁定,比如注入HttpServletRequest等,還可以接受一個目前抛出的Throwable對象。

該注解非常簡單,大多數時候其實隻@ExceptionHandler比較有用,其他兩個用到的場景非常少,這樣可以把異常處理器應用到所有控制器,而不是@Controller注解的單個控制器。

原文連結:http://jinnianshilongnian.iteye.com/blog/1866350

繼續閱讀