Spring配置檔案中 註解標籤 詳解
<context:annotation-config/>
在基於主機方式配置Spring時,Spring配置檔案applicationContext.xml,你可能會見<context:annotation-config/>
這樣一條配置,它的作用是隱式的向Spring容器註冊
AutowiredAnnotationBeanPostProcessor,
CommonAnnotationBeanPostProcessor,
PersistenceAnnotationBeanPostProcessor,
RequiredAnnotationBeanPostProcessor
這4個BeanPostProcessor。註冊這4個bean處理器主要的作用是為了你的系統能夠識別相應的註解。
例如:
- 如果想使用@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"/>
所以,如果按照傳統宣告一條一條去宣告註解Bean,就會顯得十分繁瑣。
因此如果在Spring的配置檔案中事先加上<context:annotation-config/>
這樣一條配置的話,那麼所有註解的傳統宣告就可以被 忽略,即不用在寫傳統的宣告,Spring會自動完成宣告。
<context:component-scan base-package="com.xx.xx" />
<context:component-scan/>
的作用是讓Bean定義註解工作起來,也就是上述傳統宣告方式。 它的base-package屬性指定了需要掃描的類包,類包及其遞迴子包中所有的類都會被處理。
spring的 component-scan標籤 掃描多個包:
<context:component-scan
base-package="x.y.z.service, x.y.z.controller" />
注意這裡是,分隔兩個包名,必須是 包名。
值得注意的是<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註解的類)。