spring组件扫描<context:component-scan/>详解

我们通过spring的以下方式去扫描com.test.scan.core包下所有类中的一下注解:@Repository@Service@Controller、@Component、@Configuration

<context:annotation-config />
<context:component-scan base-package="com.test.scan.core" />

 在特殊的情况下,比如一个项目涉及到多个数据源,我们写单元测试的时候,只希望每次扫描到其中一个数据源的关系类里的 @Repository@Service@Controller、@Component、@Configuration!

这里spring 给我们提供了5种方式排除不期望扫描的类中的@Repository@Service@Controller、@Component、@Configuration!

类型 举例 说明
annotation org.springframework.stereotype.Repository
指定扫描中是否扫描@Repository组件
assignable com.test.scan.core.userDaoImpl 指定是否扫描userDaoImpl.java这个类
aspectj com.test.scan..* 通过aop方式判断所扫描的范围
regex .test.* 通过正则表达式判断所扫描范围
custom 自定义过滤器 org.springframework.core.type.TypeFilter

annotation:

<context:component-scan base-package="com.test.scan.core" >
	<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Repository"/>
	<!--含义是这里我们不扫描core包下所有的@Repository注解-->
	<!--当然也可以设置为@Service、@Controller、@Component、@Configuration其中一种-->
</context:component-scan>

 assignable:

<context:component-scan base-package="com.test.scan.core" >
	<context:exclude-filter type="assignable" expression="com.test.scan.core.UserImpl"/>
	<!--含义是这里我们不扫描指定UserImpl类-->
</context:component-scan>

aspectj:

<context:component-scan base-package="com.test.scan.core" >
	<context:exclude-filter type="aspectj" expression="com.test.scan..*"/>
	<!--通过aop的方式-->
</context:component-scan>

 regex:

<context:component-scan base-package="com.test.scan.core" >
	<context:exclude-filter type="regex" expression=".test.scan.*"/>
	<!--通过aop的方式-->
</context:component-scan>

 

猜你喜欢

转载自zliguo.iteye.com/blog/2264201