1. 程式人生 > >關於Spring中的<context:annotation-config/>配置

關於Spring中的<context:annotation-config/>配置

需要 framework 方式 ota clas process lan spring容器 span

  一些小疑問,註解裝配在默認情況下是不開啟的,為了使用註解裝配,我們必須在Spring配置文件中配置 <context:annotation-config/>元素。但是在看項目源碼的時候沒有這一配置,就有些疑惑,找到了https://www.cnblogs.com/iuranus/archive/2012/07/19/2599084.html的博文,也就明白了

  當我們需要使用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/>省去。

關於Spring中的<context:annotation-config/>配置