@ComponentScans
与ComponentScan注解相对应的XML配置就是context:component-scan/, 根据指定的配置自动扫描package,将符合条件的组件加入到IOC容器中;
xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.0.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
<!-- 包扫描,只要标注了@Controller,@Service,@Repository,@Component-->
<!-- <context:component-scan base-package="cn.jbit" use-default-filters="false"></context:component-scan>-->
</beans>
注解
@ComponentScans(
value = {
@ComponentScan(value ="cn.jbit",includeFilters = {
// @ComponentScan.Filter(type = FilterType.ANNOTATION,classes = {Controller.class}),
// @ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE,classes = {BookService.class}),
@ComponentScan.Filter(type=FilterType.CUSTOM,classes = {MyTypeFilter.class})
},useDefaultFilters = false)
}
)
//ComponentScan value:指定要扫描的包
//excludeFilters = Filter[] :指定扫描的时候按照什么规则排除那些组件
//includeFilters = Filter[] :指定扫描的时候只需要那些组件
//FilterType.ANNOTATION: 按照注解
//FilterType.ASSIGNABLE_TYPE:按照给定的类型
//FilterType.CUSTOM: 自定义扫描类
自定义扫描类
/**
* 自定义扫描类
*/
public class MyTypeFilter implements TypeFilter {
/**
* @param metadataReader:读取到当前正在扫描类的信息
* @param metadataReaderFactory:可以获取到其他任何类的信息
* @return
* @throws IOException
*/
@Override
public boolean match(MetadataReader metadataReader, MetadataReaderFactory metadataReaderFactory) throws IOException {
// 获取当前类注解的信息
AnnotationMetadata annotationMetadata = metadataReader.getAnnotationMetadata();
// 获取当前正在扫描的类的信息
ClassMetadata classMetadata = metadataReader.getClassMetadata();
// 获取当前类资源(类的路径)
Resource resource = metadataReader.getResource();
String className = classMetadata.getClassName();
System.out.println("--->"+className);
if(className.contains("er")){ //包含er的类
return true;
}
return false;
}
}