1. 程式人生 > >Spring配置項<context:annotation-config>的解釋說明

Spring配置項<context:annotation-config>的解釋說明

cto org res repos ons clas div troy frame

我們一般在含有Spring的項目中,可能會看到配置項中包含這個配置節點<context:annotation-config>,這是一條向Spring容器中註冊

AutowiredAnnotationBeanPostProcessor

CommonAnnotationBeanPostProcessor

PersistenceAnnotationBeanPostProcessor

RequiredAnnotationBeanPostProcessor

這4個BeanPostProcessor.註冊這4個BeanPostProcessor的作用,就是為了你的系統能夠識別相應的註解。

那麽那些註釋依賴這些Bean呢。

如果想使用@ Resource 、@ PostConstruct、@ PreDestroy等註解就必須聲明CommonAnnotationBeanPostProcessor。
如果想使用@PersistenceContext註解,就必須聲明PersistenceAnnotationBeanPostProcessor的Bean。
如果想使用@Autowired註解,那麽就必須事先在 Spring 容器中聲明 AutowiredAnnotationBeanPostProcessor Bean。
如果想使用 @Required的註解,就必須聲明RequiredAnnotationBeanPostProcessor的Bean。

同樣,傳統的聲明方式如下:

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

但是,就一般而言,這些註解我們是經常使用,比如Antowired,Resuource等註解,如果總是按照傳統的方式一條一條的配置,感覺比較繁瑣和機械。於是Spring給我們提供了<context:annotation-config/>的簡化的配置方式,自動幫助你完成聲明,並且還自動搜索@Component , @Controller , @Service , @Repository等標註的類。

<context:component-scan base-package="com.**.impl"/>

因此當使用 <context:component-scan/> 後,就可以將 <context:annotation-config/> 移除了。

Spring配置項<context:annotation-config>的解釋說明