基于xml形式ComponentScan的使用如下
<context:component-scan base-package="com.luna" use-default-filters="false"> <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/> </context:component-scan>
基于注解@ComponentScan的使用
@Configuration
/*@ComponentScan(value = "com.luna", includeFilters = {
// @ComponentScan.Filter(type = FilterType.ANNOTATION, classes = {Controller.class}),
// @ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE,value ={com.luna.service.PersonService.class} )
@ComponentScan.Filter(type = FilterType.CUSTOM,value = {MyFilter.class})
},useDefaultFilters = false)*/
@ComponentScan(value = "com.luna",
//排除某些类
excludeFilters = { //排除Controller注解标注的类
@ComponentScan.Filter(type = FilterType.ANNOTATION, classes = {Controller.class}),
//排除指定类型的类 @ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE,value ={com.luna.service.PersonService.class} ) }) public class ScanConfig { }
测试
@Test public void test(){ AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(ScanConfig.class); String[] beanDefinitionNames = applicationContext.getBeanDefinitionNames(); Arrays.asList(beanDefinitionNames).stream().forEach(x->System.out.println("扫描到的Bean---"+x)); }
@ComponentScan一些常用参数
//基本属性 value/basePackages:指定一组要扫描的包,将扫描这些包及其子包下的文件.(默认基包为配置类所在的包)
classes:直接指定扫描的一些类,这些类所在的包及其子包也会被扫描。
nameGenerator:指定一个默认扫描组件的命名类, 默认命名使用组件类名第一个字小写。
excludeFilters:指定扫描的时候排除某些类,按什么规则,需要一组@ComponentScan.Filter的注解配置,每个@Filter可以配置一组过滤规则,多个@Filter可以基于正则/注解/具体类配置不同的过滤规则。
includeFilters:指定扫描的时候,只包含某些类。
useDefaultFilters 自动扫描Controller Component Service Resposity 这四个注解
所以在不指定明确包的情况下如 com.luna 全包扫描,会扫描到Controller Component Service Resposity 四个注解
FilterType.ANNOTATION(默认) | 一组注解,命中所有使用该注解的类,{MyAnno.class} | - |
FilterType.ASSIGNABLE_TYPE | 一组具体类 | - |
FilterType.ASPECTJ | - | 一组表达式,使用Aspectj表达式命中类 |
FilterType.REGEX | - | 一组表达式,使用正则命中类 |
FilterType.CUSTOM | 自定义的TypeFilter. | - |
全文完,感谢您的耐心阅读~
欢迎大家关注我的公众号
![](https://img2020.cnblogs.com/blog/945445/202008/945445-20200817142938521-1981960238.png)