通过在类上加注解 @ComponentScan 来扫描 Spring 的组件类。
下面三种方式都可以
@ComponentScans( @ComponentScan({"com.xxx.aaa","com.xxx.bbb"}) ) @Configuration public class Config {}
@ComponentScan({"com.xxx.aaa","com.xxx.bbb"}) @Configuration public class Config {}
@ComponentScan({"com.xxx.aaa"}) @ComponentScan({"com.xxx.bbb"}) @Configuration public class Config {}
1、过滤 @Service 注解类
@Configuration @ComponentScan( excludeFilters = { @Filter(type = FilterType.ANNOTATION, classes = Service.class) } ) public class Config {}
2、过滤 Dog 类
@Configuration @ComponentScan( excludeFilters = { @Filter(type = FilterType.ASSIGNABLE_TYPE, classes = Dog.class) } ) public class Config {}
3、正则匹配,过滤后缀为 a 的类
@Configuration @ComponentScan( excludeFilters = { @Filter(type = FilterType.REGEX, pattern = {"..*a"}) } ) public class Config {}
4、自定义过滤规则类,过滤包含 a 的类
@Configuration @ComponentScan( excludeFilters = { @Filter(type = FilterType.CUSTOM, classes = MyFilterType.class) } ) public class Config {} // 实现 TypeFilter 自定义规则:过滤包含 a 的 BeanName public class MyFilterType implements TypeFilter 自定义规则 { @Override public boolean match(MetadataReader reader, MetadataReaderFactory factory) throws IOException { return reader.getClassMetadata().getClassName().contains("a"); } }
配置类 Config,有如下规则:
@ComponentScan( value = {"com.xxx.aaa"}, excludeFilters = { @Filter(type = FilterType.ANNOTATION, classes = Service.class), @Filter(type = FilterType.ASSIGNABLE_TYPE, classes = Dog.class) } ) @ComponentScan( value = {"com.xxx.bbb"}, useDefaultFilters = false, includeFilters = { @Filter(type = FilterType.ASSIGNABLE_TYPE, classes = Cat.class) } ) @Configuration public class Config { }
Linux公社的RSS地址 : https://www.linuxidc.com/rssFeed.aspx
本文永久更新链接地址: https://www.linuxidc.com/Linux/2019-08/159933.htm