除了使用FilterType.ANNOTATION和FilterType.ASSIGNABLE_TYPE过滤规则外我们可以使用自定义规则来进行过滤
需要实现TypeFilter接口
@Filter(type=FilterType.CUSTOM,classes={MyTypeFilters.class}
实例如下
package com.zyc.spring.config;
import java.io.IOException;
import org.springframework.core.io.Resource;
import org.springframework.core.type.AnnotationMetadata;
import org.springframework.core.type.ClassMetadata;
import org.springframework.core.type.classreading.MetadataReader;
import org.springframework.core.type.classreading.MetadataReaderFactory;
import org.springframework.core.type.filter.TypeFilter;
public class MyTypeFilter implements TypeFilter{
@Override
public boolean match(MetadataReader metadataReader, MetadataReaderFactory metadataReaderFactory)
throws IOException {
//获取当前类注解信息
AnnotationMetadata annotationMetadate = metadataReader.getAnnotationMetadata();
//获取当前正在扫描的类的信息
ClassMetadata classMethod = metadataReader.getClassMetadata();
//获取当前类资源
Resource resource = metadataReader.getResource();
String className = classMethod.getClassName();
if(className.contains("er")){
return true;
}
return false;
}
}
配置类
package com.zyc.spring.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.ComponentScan.Filter;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.FilterType;
import org.springframework.stereotype.Controller;
import com.zyc.spring.bean.Person;
import com.zyc.spring.service.BookService;
//配置类
@Configuration
@ComponentScan(value="com.zyc.spring",includeFilters={
@Filter(type=FilterType.CUSTOM,classes={MyTypeFilter.class})},
useDefaultFilters = false)
public class MainConfig {
@Bean("person1")
public Person person(){
return new Person("li",9);
}
}