- <context:annotation-config/>
AutowiredAnnotationBeanPostProcessor,
CommonAnnotationBeanPostProcessor,
PersistenceAnnotationBeanPostProcessor,
RequiredAnnotationBeanPostProcessor
這4個BeanPostProcessor.注冊這4個bean處理器主要的作用是為了你的系統能夠識別相應的注解。
例如:
因此如果在Spring的配置文件中事先加上 <context:annotation-config/>這樣一條配置的話,那么所有注解的傳統聲明就可以被 忽略,即不用在寫傳統的聲明,Spring會自動完成聲明。
值得注意的是 <context:component-scan/>不但啟用了對類包進行掃描以實施注釋驅動 Bean 定義的功能,同時還啟用了注釋驅動自動注入的功能(即還隱式地在內部注冊了 AutowiredAnnotationBeanPostProcessor 和 CommonAnnotationBeanPostProcessor),因此當使用 <context:component-scan/> 后,就可以將 <context:annotation-config/> 移除了。
例如:
- 如果想使用@Autowired注解,需要在Spring容器中聲明AutowiredAnnotationBeanPostProcessor Bean。傳統的聲明方式:<bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/>
- 如果想使用@PersistenceContext注解,需要在Spring容器中聲明PersistenceAnnotationBeanPostProcessor Bean。傳統的聲明:<bean class="org.springframework.beans.factory.annotation.RequiredAnnotationBeanPostProcessor"/>
- 如果想使用@Required注解,需要在Spring容器中聲明RequiredAnnotationBeanPostProcessor Bean。傳統聲明方式:<bean class="org.springframework.beans.factory.annotation.RequiredAnnotationBeanPostProcessor"/>
- 如果想使用@Resource、@ PostConstruct、@ PreDestroy等注解就必須聲明CommonAnnotationBeanPostProcessor。傳統申明方式: <bean class="org.springframework.beans.factory.annotation.CommonAnnotationBeanPostProcessor"/>
因此如果在Spring的配置文件中事先加上 <context:annotation-config/>這樣一條配置的話,那么所有注解的傳統聲明就可以被 忽略,即不用在寫傳統的聲明,Spring會自動完成聲明。
-
<context:component-scan base-package="com.xx.xx" />
值得注意的是 <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注解的類)。