Spring中的作用

最近在研究spring中<context:annotation-config/>配置的作用,現記錄如下:

<context:annotation-config/>的作用是向Spring容器註冊以下四個BeanPostProcessor:

  • AutowiredAnnotationBeanPostProcessor
  • CommonAnnotationBeanPostProcessor
  • PersistenceAnnotationBeanPostProcessor
  • RequiredAnnotationBeanPostProcessor
那麼,爲什麼要註冊這四個BeanPostProcessor呢?

是爲了讓系統能夠識別相應的註解。

例如:

1、如果想使用@Autowired註解,那麼就必須事先在 Spring 容器中聲明 AutowiredAnnotationBeanPostProcessor Bean。

傳統聲明方式如下:

<bean class="org.springframework.beans.factory.annotation. AutowiredAnnotationBeanPostProcessor "/> 

2、如果想使用@ Resource 、@ PostConstruct、@ PreDestroy等註解就必須聲明CommonAnnotationBeanPostProcessor  Bean。

3、如果想使用@PersistenceContext註解,就必須聲明PersistenceAnnotationBeanPostProcessor的Bean。

4、如果想使用@Required的註解,就必須聲明RequiredAnnotationBeanPostProcessor的Bean。


以上這些註解是很常用的,如果按照傳統的方式進行配置將會非常繁瑣,所以Spring給我們提供了一個簡便的方式:<context:annotation-config/>,使用該元素可以自動聲明以上註解。

注:由於<context:component-scan base-package=”xx.xx”/>也包含了自動注入上述Bean的功能,所以<context:annotation-config/> 可以省略。如果兩者都進行了配置,則只有前者有效。


注:

<context:annotation-config> 是用於激活那些已經在spring容器裏註冊過的bean(無論是通過xml的方式還是通過package sanning的方式)上面的註解。

<context:component-scan>除了具有<context:annotation-config>的功能之外,<context:component-scan>還可以在指定的package下掃描以及註冊javabean 。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章