Spring組件掃描使用詳解

 

1.若是不想在xml文件中配置bean,咱們能夠給咱們的類加上spring組件註解,只需再配置下spring的掃描器就能夠實現bean的自動載入。<!-- 註解注入 -->spring

<context:annotation-config></context:annotation-config>express

<context:component-scan base-package="com.liantuo.hotel.common.service.impl" />app

<context:component-scan base-package="com.liantuo.hotel.common.dao.ibatis" />工具

<context:component-scan base-package="com.liantuo.hotel.app.dao.ibatis" />spa

<context:component-scan base-package="com.liantuo.hotel.app.service" />.net

<context:component-scan base-package="com.liantuo.hotel.app.service.ibatis" />code

2.下面是引用spring framework開發手冊中的一段話component

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已經能在持久化層中進行異常轉換時被做爲標記使用了。」xml

3.有了<context:component-scan>,另外一個<context:annotation-config/>標籤根本能夠移除掉,由於已經被包含進去了。ip

4.<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>

5.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
相關文章
相關標籤/搜索