当我们在Spring配置中增加<context:annotetion-config>时,我们希望Spring特殊对待我们所定义的Bean里的一组注解,并使用这些注解指导Bean装配。即使<context:annotetion-config>有助于完全消除Spring配置中的<property>和<construct-arg>元素,我们仍需要使用<bean>元素显式定义Bean。<context:component-scan>元素除了完成与<context:annotetion-config>一样的工作,还允许Spring自动检测Bean和定义Bean。这意味着不适用<bean>元素,Spring应用中的大多数bean都能够实现定义和装配。
为了配置Spring自动检测,需要使用<context:component-scan>元素来代替<context:annotetion-config>元素
<context:component-scan>元素会扫描指定的包及其所有子包,并查找出能够自动注册为Spring Bean的类。base-package属性标识了<context:component-scan>元素所扫描的包。
一、为自动检测标注Bean
默认情况下,<context:component-scan>元素查找使用构造型注解所标注的类,这些特殊的注解如下。
@Component @Controller @Repository @Service
二、过滤组件扫描
事实上,在如何扫描来获得候选Bean方面,<context:component-scan>非常灵活。通过为<context:component-scan>配置<context:include-filter>或者<context:exclude-filter>子元素,我们可以随意调整扫描行为。
过滤器类型包括annotation、assignable、aspect、custom、regex