context命名空间的component-scan通过扫描base-package属性指定的类包,从类的注解信息中获取bean的定义信息
<context:component-scan base-package="com.xxx" use-default-filters="true"/>
并通过<context:include-filter>和<context:exclude-filter>对信息进行过滤:
<context:component-scan base-package="com.xxx" use-default-filters="false">
<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller" />
</context:component-scan>
<context:component-scan base-package="com.xxx">
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller" />
</context:component-scan>
其中,use-default-filters是一个不容忽视的属性,默认值为true,表示默认会对@Component、@Controller、@Service、@Reposity标注的bean进行扫描。<context:component-scan>先根据<context:exclude-filter>列出需要排除的黑名单,再通过<context:include-filter>列出需要包含的白名单。
下面的反例中,不但会扫描@Controller的bean,还会扫描@Component、@Service、@Reposity的bean
<context:component-scan base-package="com.xxx">
<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller" />
</context:component-scan>
原因如上所述,use-default-filters默认为true,所以要显示指定为false
<context:component-scan base-package="com.xxx" use-default-filters="false">
<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller" />
</context:component-scan>
总结:属性use-default-filters="false"和<context:include-filter>要一起使用,表示:只扫描指定注解的类。
<context:exclude-filter>直接使用,表示:不扫描指定注解的类,其他注解类全部扫描。