" type="hidden"/>

Spring配置文件詳解:


  • <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.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方法了。
注意:如果有多個配置文件,在最頂層的配置文件(啟動類所在的配置文件)中加入<context:component-scan base-package="com.xx.xx" /> 。(如controller層的配置文件中)
  • <mvc:annotation-driven />

它會自動注冊DefaultAnnotationHandlerMapping 與AnnotationMethodHandlerAdapter

結論:在spring-servlet.xml中只需要掃描所有帶@Controller注解的類,在applicationContext中可以掃描所有其他帶有注解的類(也可以過濾掉帶@Controller注解的類)。


免責聲明!

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



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