天天看點

Spring注解之xml配置中的<context:component-scan />和<context:annotation-config/>

今天偶然看見項目中的applicationContext.xml配置檔案,就想起來曾經學習的時候比較困惑一個問題:<context:component-scan />和<context:annotation-config/> 這兩種注解配置到底有啥差別??。。其實到今天如果不是看文章估計我還是迷迷糊糊的,不喜歡探究的程式員不是好java工程師。。

Spring注解之xml配置中的&lt;context:component-scan /&gt;和&lt;context:annotation-config/&gt;

首先從<context:annotation-config/>說起

<context:annotation-config/>篇

他的作用是式地向 Spring 容器注冊

AutowiredAnnotationBeanPostProcessor、
CommonAnnotationBeanPostProcessor、
PersistenceAnnotationBeanPostProcessor、
RequiredAnnotationBeanPostProcessor 
           

注冊這4個 BeanPostProcessor的作用,就是為了你的系統能夠識别相應的注解。說白了,如果你想使用@Autowired注解,那麼就必須事先在 spring 容器中聲明

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

如果想使用@ Resource 、@ PostConstruct、@ PreDestroy等注解就必須聲明CommonAnnotationBeanPostProcessor

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

如果想使用@Required的注解,就必須聲明RequiredAnnotationBeanPostProcessor的Bean。同樣,傳統的聲明方式如下:

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

一般來說,這些注解我們還是比較常用,尤其是Antowired的注解,在自動注入的時候更是經常使用,是以如果總是需要按照傳統的方式一條一條配置顯得有些繁瑣和沒有必要,于是spring給我們提供<context:annotation-config/>的簡化配置方式,自動幫你完成聲明。

但是你可能也注意到了現在的注解很多,僅僅這幾個注解恐怕是不夠的,不怕一萬就怕萬一。。。。。。。。。。。。。。

比如這幾個就沒有:@component,@service,@Repository,@Controller

<context:component-scan />篇

Spring 2.5引入了更多典型化注解(stereotype annotations):

@Component

@Service

@Controller

@Component

是所有受Spring管理元件的通用形式;

@Repository

@Service

@Controller

則是

@Component

的細化,用來表示更具體的用例(例如,分别對應了持久化層、服務層和表現層)。也就是說,你能用

@Component

來注解你的元件類,但如果用

@Repository

@Service

@Controller

來注解它們,你的類也許能更好地被工具處理,或與切面進行關聯。例如,這些典型化注解可以成為理想的切入點目标。當然,在Spring Framework以後的版本中,

@Repository

@Service

@Controller

也許還能攜帶更多語義。如此一來,如果你正在考慮服務層中是該用

@Component

還是

@Service

,那

@Service

顯然是更好的選擇。同樣的,就像前面說的那樣,

@Repository

已經能在持久化層中進行異常轉換時被作為标記使用了。”

其他的先不說就單單說他的包過濾就感覺很好:

<context:component-scan>提供兩個子标簽:<context:include-filter>和<context:exclude-filter>各代表引入和排除的過濾。 如: <context:component-scan base-package="com.xhlx.finance.budget" > <context:include-filter type="regex" expression=".service.*"/>

</context:component-scan> filter标簽在Spring3有五個type,如下:

Filter Type Examples Expression Description
annotation org.example.SomeAnnotation 符合SomeAnnoation的target class
assignable org.example.SomeClass 指定class或interface的全名
aspectj org.example..*Service+ AspectJ文法
regex org\.example\.Default.* Regelar Expression
custom org.example.MyTypeFilter Spring3新增自訂Type,實作org.springframework.core.type.TypeFilter

綜上所述:一般的話還是使用<context:component-scan />吧!因為他不僅包含了<context:annotation-config/>還包含了其他的注解,特别是現在springMVC這麼火的時候。。。

繼續閱讀