<context:annotation-config/>

  • <context:annotation-config/>
    在基於主機方式配置Spring時,Spring配置文件applicationContext.xml,你可能會見<context:annotation-config/>這樣一條配置,它的作用是隱式的向Spring容器註冊
                           AutowiredAnnotationBeanPostProcessor,
                           CommonAnnotationBeanPostProcessor,
                           PersistenceAnnotationBeanPostProcessor,
                           RequiredAnnotationBeanPostProcessor 
 這4個BeanPostProcessor.註冊這4個bean處理器主要的作用是爲了你的系統能夠識別相應的註解。                        
 例如:
  1.  如果想使用@Autowired註解,需要在Spring容器中聲明AutowiredAnnotationBeanPostProcessor Bean。傳統的聲明方式:<bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/>
  2. 如果想使用@PersistenceContext註解,需要在Spring容器中聲明PersistenceAnnotationBeanPostProcessor Bean。傳統的聲明:<bean class="org.springframework.beans.factory.annotation.RequiredAnnotationBeanPostProcessor"/>
  3. 如果想使用@Required註解,需要在Spring容器中聲明RequiredAnnotationBeanPostProcessor Bean。傳統聲明方式: <bean class="org.springframework.beans.factory.annotation.RequiredAnnotationBeanPostProcessor"/>
  4. 如果想使用@Resource、@ PostConstruct、@ PreDestroy等註解就必須聲明CommonAnnotationBeanPostProcessor。傳統申明方式: <bean class="org.springframework.beans.factory.annotation.CommonAnnotationBeanPostProcessor"/>
所以,如果按照傳統聲明一條一條去聲明註解Bean,就會顯得十分繁瑣。
因此如果在Spring的配置文件中事先加上
<context:annotation-config/>這樣一條配置的話,那麼所有註解的傳統聲明就可以被  忽略,即不用在寫傳統的聲明,Spring會自動完成聲明

  • <context:component-scan base-package="com.xx" /> 

  <context:component-scan/>的作用是讓Bean定義註解工作起來,也就是上述傳統聲明方式。 它的base-package屬性指定了需要掃描的類包,類包及其遞歸子包中所有的類都會被處理。

     值得注意的是<context:component-scan/>不但啓用了對類包進行掃描以實施註釋驅動 Bean 定義的功能,同時還啓用了註釋驅動自動注入的功能(即還隱式地在內部註冊了 AutowiredAnnotationBeanPostProcessor 和 CommonAnnotationBeanPostProcessor),因此當使用 <context:component-scan/> 後,就可以將 <context:annotation-config/> 移除了。
 
 @Autowired可以對成員變量、方法和構造函數進行標註,來完成自動裝配的工作。@Autowired的標註位置不同,它們都會在Spring在初始化這個bean時,自動裝配這個屬性。註解之後就不需要set/get方法了。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章