@ControllerAdvice


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

@Target(ElementType.TYPE)  
@Retention(RetentionPolicy.RUNTIME)  
@Documented  
@Component  
public @interface ControllerAdvice {  
  
} 

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

其javadoc定義是:

寫道
/**
* Indicates the annotated class assists a "Controller".
*
* <p>Serves as a specialization of {@link Component @Component}, allowing for
* implementation classes to be autodetected through classpath scanning.
*
* <p>It is typically used to define {@link ExceptionHandler @ExceptionHandler},
* {@link InitBinder @InitBinder}, and {@link ModelAttribute @ModelAttribute}
* methods that apply to all {@link RequestMapping @RequestMapping} methods.
*
* @author Rossen Stoyanchev
* @since 3.2
*/

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

 

接下來看段代碼:

@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

<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包含進來,否則不起作用:

<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>  

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

@ControllerAdvice -- 示例

啦啦啦


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM