context:annotation-config, mvc:annotation-driven, context:compont-scan 區別


  當我們需要使用BeanPostProcessor時,直接在Spring配置文件中定義這些Bean顯得比較笨拙,例如:
  使用@Autowired注解,必須事先在Spring容器中聲明AutowiredAnnotationBeanPostProcessor的Bean:

<bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor "/>

  使用 @Required注解,就必須聲明RequiredAnnotationBeanPostProcessor的Bean:

<bean class="org.springframework.beans.factory.annotation.RequiredAnnotationBeanPostProcessor"/>

  類似地,使用@Resource、@PostConstruct、@PreDestroy等注解就必須聲明 CommonAnnotationBeanPostProcessor;使用@PersistenceContext注解,就必須聲明 PersistenceAnnotationBeanPostProcessor的Bean。
  這樣的聲明未免太不優雅,而Spring為我們提供了一種極為方便注冊這些BeanPostProcessor的方式,即使用<context:annotation- config/>隱式地向 Spring容器注冊AutowiredAnnotationBeanPostProcessor、RequiredAnnotationBeanPostProcessor、CommonAnnotationBeanPostProcessor以及PersistenceAnnotationBeanPostProcessor這4個BeanPostProcessor。如下:

<context:annotation-config/> 

  另,在我們使用注解時一般都會配置掃描包路徑選項:

<context:component-scan base-package="pack.pack"/>

  該配置項其實也包含了自動注入上述processor的功能,因此當使用<context:component-scan/>后,即可將<context:annotation-config/>省去。

<mvc:annotation-driven/>
相當於注冊了DefaultAnnotationHandlerMapping和AnnotationMethodHandlerAdapter兩個bean,配置一些messageconverter。即解決了@Controller注解的使用前提配置。

<mvc:annotation-driven/> is a tag added in Spring 3.0 which does the following: 

1. Configures the Spring 3 Type ConversionService (alternative to PropertyEditors) 
2. Adds support for formatting Number fields with @NumberFormat 
3. Adds support for formatting Date, Calendar, and Joda Time fields with @DateTimeFormat, if Joda Time is on the classpath 
4. Adds support for validating @Controller inputs with @Valid, if a JSR-303 Provider is on the classpath 
5. Adds support for support for reading and writing XML, if JAXB is on the classpath (HTTP message conversion with @RequestBody/@ResponseBody) 
6. Adds support for reading and writing JSON, if Jackson is o n the classpath (along the same lines as #5) 


免責聲明!

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



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