1.CustomerImportSelector工具类:
package com.itheima.config.selector;
import org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.ImportSelector;
import org.springframework.core.io.support.PropertiesLoaderUtils;
import org.springframework.core.type.AnnotationMetadata;
import org.springframework.core.type.filter.AspectJTypeFilter;
import org.springframework.core.type.filter.TypeFilter;
import java.io.IOException;
import java.util.*;
public class CustomerImportSelector implements ImportSelector {
private String expression;
public CustomerImportSelector(){
try {
Properties loadAllProperties = PropertiesLoaderUtils.loadAllProperties("import2.properties");
expression = loadAllProperties.getProperty("className");
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public String[] selectImports(AnnotationMetadata importingClassMetadata) {
String[] basePackages = null;
if (importingClassMetadata.hasAnnotation(ComponentScan.class.getName())) {
Map<String, Object> annotationAttributes = importingClassMetadata.getAnnotationAttributes(ComponentScan.class.getName());
basePackages = (String[]) annotationAttributes.get("basePackages");
}
if (basePackages == null || basePackages.length == 0) {
String basePackage = null;
try {
basePackage = Class.forName(importingClassMetadata.getClassName()).getPackage().getName();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
basePackages = new String[] {basePackage};
}
ClassPathScanningCandidateComponentProvider scanner = new ClassPathScanningCandidateComponentProvider(false);
TypeFilter typeFilter = new AspectJTypeFilter(expression,this.getClass().getClassLoader());
scanner.addIncludeFilter(typeFilter);
Set<String> classes = new HashSet<>();
for (String basePackage : basePackages) {
scanner.findCandidateComponents(basePackage).forEach(beanDefinition -> classes.add(beanDefinition.getBeanClassName()));
}
return classes.toArray(new String[classes.size()]);
}
}
2.import2.properties属性文件
- 表示className=com.itheima.dao.impl下的bean对象不需要用@Repository("")配置,自动导入
- 应用场景,接口实现类较多,可采用导入器自动注入
className=com.itheima.dao.impl.*
3.导入SpringConfig类中加载
@Import(CustomerImportSelector.class)
public class SpringConfig {
}
4.所需classpath依赖
<dependency>
<groupId> org.aspectj</groupId >
<artifactId> aspectjweaver</artifactId >
<version> 1.8.7</version >
</dependency>