1. component-scan
在xml文件配置了<context:component-scan>标签后,spring容器可以自动去扫描base-package所指定的包或其子包下面的java类文件,如果扫描到有@Component、@Controller、@Service 、@Repository等注解修饰的Java类,则将这些类注册为spring容器中的bean。
注意:
- 如果配置了
<context:component-scan>标签元素,那么<context:annotation-config/>标签就可以不用在xml中配置了,因为前者包含了后者。
1.1. 元素属性
base-package
- 是否必填:yes
- 默认值:
- 属性描述:要描述的包,多个包路径可以用,号;号分隔
- 示例:
<context:component-scan base-package="samples.spring.cscan"/>,此配置意味着会扫描samples.spring.cscan包下的所有标有@Component注解的类,并注册为bean。
use-default-filters
- 是否必填:no
- 默认值:true
- 属性描述:是否使用默认的过滤器
- 示例:
annotation-config
- 是否必填:no
- 默认值:true
- 属性描述:是否注册注解配置处理器bean
- 示例:
- 说明:
name-generator
- 是否必填:no
- 默认值:
- 属性描述:bean name 生成器
- 示例:
- 说明:
scope-resolver
scoped-proxy
resource-pattern
1.2. 子标签
默认情况下,Spring会扫描所有标有@Component注解(包括其子注解@Service、@Repository、@Controller等)的类,并将其注册为bean。除此之外,<context:component-scan>提供两个子标签用于引入和排除过滤:
<context:include-filter>:指定引用扫描的过滤器,用于引入想进行扫描的类;<context:exclude-filter>:指定排队扫描的过滤器,用于排除不想进行扫描的类;
1.2.1. xml示例
annotation
<context:component-scan base-package="samples.spring.cscan">
<!-- 不扫描Controller注解 -->
<context:exclude-filter type="annotation"
expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
指定扫描中是否扫描@Controller组件
assignable
<context:component-scan base-package="samples.spring.cscan">
<!-- 不描述MyService2类 -->
<context:exclude-filter type="assignable" expression="samples.spring.cscan.service.MyService2"/>
</context:component-scan>
指定是否扫描MyService2.java这个类
aspectj
<context:component-scan base-package="com.test.scan.core" >
<context:exclude-filter type="aspectj" expression="com.test.scan..*"/>
<!--通过aop的方式-->
</context:component-scan>
通过aop方式判断所扫描的范围
regex
<context:component-scan base-package="com.test.scan.core" >
<context:exclude-filter type="regex" expression=".test.scan.*"/>
<!--通过aop的方式-->
</context:component-scan>
通过正则表达式判断所扫描范围
custom
自定义过滤器
1.2.2. filter 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 |