目录
ASSIGNABLE_TYPE、按指定类型来判定,也比较常用
前沿
上篇文章我们讲解了@CompontScan的使用,比如我们在includeFilters中使用type = FilterType.ANNOTATION,classes = {Controller.class}来指定type。
类型
这里我们使用的是ANNOTATION,其实这里的type有以下几种类型
ANNOTATION、按注解类型来判定,也是最常用的
ASSIGNABLE_TYPE、按指定类型来判定,也比较常用
@ComponentScan(basePackages = {"com.zhujie"},includeFilters = {
@ComponentScan.Filter(type = FilterType.ANNOTATION,classes = {Controller.class}),
@ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE,classes = {UserService.class})
ASPECTJ使用aspectj表达式,不怎么用
REGEX使用正则表达式,不怎么用
CUSTOM自定义规则
首先得写一个实现了TypeFilter的实现类
public class MyTypeFilter implements TypeFilter {
/**
*
* @param metadataReader 当前类扫描的信息
* @param metadataReaderFactory 可以获取其他任何类的信息
* @return
* @throws IOException
*/
@Override
public boolean match(MetadataReader metadataReader, MetadataReaderFactory metadataReaderFactory) throws IOException {
//获取被扫描的类的全类名
String className = metadataReader.getClassMetadata().getClassName();
System.out.println(className+"----------");
if(className.contains("troller")){
// 如果类名中包含有troller则被注册到组件
return true;
}
return false;
}
}
然后再配置类中自定义即可
@Configuration
@ComponentScan(basePackages = {"com.zhujie"},includeFilters = {
@ComponentScan.Filter(type = FilterType.CUSTOM,classes = {MyTypeFilter.class})
},useDefaultFilters = false)
//excludeFilters 是一个数组
public class MainConfig {
@Bean("use")
public User getUser(){
return new User(1001,"张三");
}
}
在运行之前的测试类会看到只有controller被注册到容器中