1品山、Spring-SpringMVC項(xiàng)目中一般都會(huì)把a(bǔ)pplicationContext.xml (Spring配置文件)和spring-mvc.xml(SpringMVC配置文件)進(jìn)行分開(kāi)配置画恰。
在applicationContext.xml 只對(duì)一些事務(wù)邏輯的注解掃描:@Component敦冬、@Repository、@Service
在Spring-common.xml中只對(duì)控制器注解掃描:@Controller、@RestController梦染、@ControllerAdvice
2、了解component-scan的幾個(gè)屬性
basePackages:Spring將掃描的基礎(chǔ)package名朴皆,Spring會(huì)掃描該包以及其子孫包下的所有類
useDefaultFilters:默認(rèn)為true帕识,此時(shí)Spring掃描類時(shí)發(fā)現(xiàn)如果其被標(biāo)注為 @Component、@Repository遂铡、@Service肮疗、@Controller則自動(dòng)實(shí)例化為bean并將其添加到上下文中,如果設(shè)置為false扒接,即使將其標(biāo)注為@Component或者其他伪货,Spring都會(huì)忽略
includeFilters: 指定掃描時(shí)需要實(shí)例化的類型,我們可以從名字看到這是一個(gè)Filter钾怔,你可以自己定義該Filter碱呼,Spring為我們提供了一套方便的實(shí)現(xiàn),我們可以根據(jù)標(biāo)注蒂教、類巍举、包等相關(guān)信息決定當(dāng)掃描到該類時(shí)是否需要實(shí)例化該類,需要注意的是如果你僅僅想掃描如@Controller不僅要加includeFilters凝垛,還需要將useDefaultFilters設(shè)置為false
excludeFilter:指定掃描到某個(gè)類時(shí)需要忽略它懊悯,實(shí)現(xiàn)和上一個(gè)Filter一樣,區(qū)別只是如果Filter匹配梦皮,Spring會(huì)忽略該類
這樣includeFilters以及excludeFilterF的行為就很清楚了炭分,Spring每掃描一個(gè)類,都會(huì)經(jīng)過(guò)includeFilters以及excludeFilters剑肯,如果某個(gè)Filter匹配捧毛,就執(zhí)行相應(yīng)的操作(實(shí)例化或者忽略)
3、applicationContext.xml 以及 spring-mvc.xml 自動(dòng)掃描注解的配置實(shí)例
applicationContext.xml
<!-- 使用annotation 自動(dòng)注冊(cè)bean,并檢查@Required,@Autowired的屬性已被注入 -->
<context:component-scan base-package="com.zx.stlife">
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
<context:exclude-filter type="annotation" expression="org.springframework.web.bind.annotation.RestController"/>
<context:exclude-filter type="annotation" expression="org.springframework.web.bind.annotation.ControllerAdvice"/>
</context:component-scan>
spring-mvc.xml
<!-- 自動(dòng)掃描且只掃描@Controller -->
<context:component-scan base-package="com.zx.stlife.controller" use-default-filters="false">
<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
<context:include-filter type="annotation" expression="org.springframework.web.bind.annotation.RestController"/>
<context:include-filter type="annotation" expression="org.springframework.web.bind.annotation.ControllerAdvice"/>
</context:component-scan>