Spring3.2新注解@ControllerAdvice
@ControllerAdvice,是spring3.2提供的新注解,從名字上可以看出大體意思是控制器增強。讓我們先看看@ControllerAdvice的實作:
Java代碼
- @Target(ElementType.TYPE)
- @Retention(RetentionPolicy.RUNTIME)
- @Documented
- @Component
- public @interface ControllerAdvice {
- }
沒什麼特别之處,該注解使用@Component注解,這樣的話當我們使用<context:component-scan>掃描時也能掃描到,
其javadoc定義是:
寫道
即把@ControllerAdvice注解内部使用@ExceptionHandler、@InitBinder、@ModelAttribute注解的方法應用到所有的 @RequestMapping注解的方法。非常簡單,不過隻有當使用@ExceptionHandler最有用,另外兩個用處不大。
接下來看段代碼:
Java代碼
- @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"; //傳回一個邏輯視圖名
- }
- }
如果你的spring-mvc配置檔案使用如下方式掃描bean
Java代碼
- <context:component-scan base-package="com.sishuok.es" use-default-filters="false">
- <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
- </context:component-scan>
需要把@ControllerAdvice包含進來,否則不起作用:
Java代碼
- <context:component-scan base-package="com.sishuok.es" use-default-filters="false">
- <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
- <context:include-filter type="annotation" expression="org.springframework.web.bind.annotation.ControllerAdvice"/>
- </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