1. 程式人生 > >Spring配置項<context:component-scan/>和<context:annotation-config/>

Spring配置項<context:component-scan/>和<context:annotation-config/>

<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/>的簡化的配置方式。

注意:即使你使用了<context:annotation-config/>註解,以@Autowired為例,對於需要注入的Bean,仍然還要在xml中手動宣告。這樣很不方便,因此就引出了下面的<context:component-scan>註解。

 

<context:component-scan>

<context:component-scan>首先有和<context:annotation-config/>一樣的作用,此外,它還可以掃描指定包下的類,將擁有註解的它們註冊到Spring容器中。

 

綜上,也就是說,如果用<context:annotation-config/>,我們還需要配置Xml註冊Bean,而使用<context:component-scan />的話,註冊的步驟都免了,當然前提是我們對需要掃描的類使用的註解(比如@Componet,@Service),而如果同時使用兩個配置的話,<context:annotation-config/>會被忽略掉。