@ComponentScan常用参数
basePackages:对basepackages()指定扫描注释组件包类型安全的替代。
excludeFilters:指定不适合组件扫描的类型。
includeFilters:指定哪些类型有资格用于组件扫描。
lazyInit:指定是否应注册扫描的beans为lazy初始化。
nameGenerator:用于在Spring容器中的检测到的组件命名。
resourcePattern:控制可用于组件检测的类文件。
scopedProxy:指出代理是否应该对检测元件产生,在使用过程中会在代理风格时尚的范围是必要的。
scopeResolver:用于解决检测到的组件的范围。
useDefaultFilters:指示是否自动检测类的注释
@Component
@Repository
,
@Service
, or
@Controller
应启用。
value:
basePackages()别名
@ComponentScan(value = "com.annotation",useDefaultFilters = false,
includeFilters = {@ComponentScan.Filter(type = FilterType.ANNOTATION,classes = {Controller.class,ControllerAdvice.class})})
@ComponentScan(basePackages = {"spittr"},
excludeFilters = {@Filter(type = FilterType.ANNOTATION, value = EnableWebMvc.class)})
@Filter
ANNOTATION:注解类型
ASSIGNABLE_TYPE:ANNOTATION:指定的类型
ASPECTJ:按照Aspectj的表达式,基本上不会用到
REGEX:按照正则表达式
CUSTOM:自定义规则
下面说一下CUSTOMER类型的用法:
具体的配置可以这样写:
@ComponentScan(value = "com.annotation",useDefaultFilters = false,
includeFilters = {
// @ComponentScan.Filter(type = FilterType.ANNOTATION,classes = {Controller.class,ControllerAdvice.class}),
// @ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE,classes = {PersonDao.class}),
@ComponentScan.Filter(type = FilterType.CUSTOM,classes = {MyFilterType.class})
}
)
其中MyFilterType是我自己写的一个类,它需要实现TypeFilter接口,实现接口需要重写一个方法match(),当match()方法返回true,则当前扫描的类被放入spring容器中,返回false则不放入容器中。我这里规定类名中包含“Employee”的返回true,即将其放入到容器中,否则返回false不放入到容器中:
public class MyFilterType implements TypeFilter {
@Override
public boolean match(MetadataReader metadataReader, MetadataReaderFactory metadataReaderFactory) throws IOException {
if (metadataReader.getClassMetadata().getClassName().contains("Department")){
//获取当前类注解的信息
AnnotationMetadata annotationMetadata = metadataReader.getAnnotationMetadata();
for (String s : annotationMetadata.getAnnotationTypes()) {
System.out.println("当前正在被扫描的类注解类型" + s);
}
//获取当前正在扫描类的信息
ClassMetadata classMetadata = metadataReader.getClassMetadata();
System.out.println("当前正在被扫描的类的类名" + classMetadata.getClassName());
//获取当前类的资源信息(类存放的路径...)
Resource resource = metadataReader.getResource();
System.out.println("当前正在被扫描的类存放的地址" + resource.getURL());
return true;
}
return false;
}
}
当前正在被扫描的类的类名com.annotation.entities.Department
当前正在被扫描的类存放的地址file:/D:/DevInstall/Project/annotation/target/classes/com/annotation/entities/Department.class
当前正在被扫描的类注解类型org.springframework.web.bind.annotation.ControllerAdvice
当前正在被扫描的类的类名com.annotation.handler.DepartmentHandler
当前正在被扫描的类存放的地址file:/D:/DevInstall/Project/annotation/target/classes/com/annotation/handler/DepartmentHandler.class
当前正在被扫描的类注解类型org.springframework.stereotype.Service
当前正在被扫描的类的类名com.annotation.service.DepartmentService
当前正在被扫描的类存放的地址file:/D:/DevInstall/Project/annotation/target/classes/com/annotation/service/DepartmentService.class