解决方案1:弹簧方式
最简单的答案是遵循 spring 子项目 (boot,data...) 如何实现这种类型的需求。他们通常定义一个自定义组合注释来启用该功能并定义一组要扫描的包。
例如给出这个注释:
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Import({MyInterfaceScanRegistrar.class})
public @interface MyInterfaceScan {
String[] value() default {};
}
Wherevalue
定义要扫描的包并@Import
启用MyInterfaceScan
检测。
然后创建ImportBeanDefinitionRegistrar
. 这个类将能够创建bean定义
在处理 @Configuration 类时注册附加 bean 定义的类型实现的接口。在需要或必须在 bean 定义级别(相对于 @Bean 方法/实例级别)操作时很有用。
public class MyInterfaceScanRegistrar implements ImportBeanDefinitionRegistrar, EnvironmentAware {
private Environment environment;
@Override
public void setEnvironment(Environment environment) {
this.environment = environment;
}
@Override
public void registerBeanDefinitions(AnnotationMetadata metadata, BeanDefinitionRegistry registry) {
// Get the MyInterfaceScan annotation attributes
Map<String, Object> annotationAttributes = metadata.getAnnotationAttributes(MyInterfaceScan.class.getCanonicalName());
if (annotationAttributes != null) {
String[] basePackages = (String[]) annotationAttributes.get("value");
if (basePackages.length == 0){
// If value attribute is not set, fallback to the package of the annotated class
basePackages = new String[]{((StandardAnnotationMetadata) metadata).getIntrospectedClass().getPackage().getName()};
}
// using these packages, scan for interface annotated with MyCustomBean
ClassPathScanningCandidateComponentProvider provider = new ClassPathScanningCandidateComponentProvider(false, environment){
// Override isCandidateComponent to only scan for interface
@Override
protected boolean isCandidateComponent(AnnotatedBeanDefinition beanDefinition) {
AnnotationMetadata metadata = beanDefinition.getMetadata();
return metadata.isIndependent() && metadata.isInterface();
}
};
provider.addIncludeFilter(new AnnotationTypeFilter(MyCustomBean.class));
// Scan all packages
for (String basePackage : basePackages) {
for (BeanDefinition beanDefinition : provider.findCandidateComponents(basePackage)) {
// Do the stuff about the bean definition
// For example, redefine it as a bean factory with custom atribute...
// then register it
registry.registerBeanDefinition(generateAName() , beanDefinition);
System.out.println(beanDefinition);
}
}
}
}
}
这是逻辑的核心。bean 定义可以作为具有属性的 bean 工厂进行操作和重新定义,也可以使用从接口生成的类重新定义。
MyCustomBean
是一个简单的注释:
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface MyCustomBean {
}
这可以注释一个接口:
@MyCustomBean
public interface Class1 {
}
解决方案2:提取组件扫描
提取包定义的代码@ComponentScan
将更加复杂。
您应该创建一个BeanDefinitionRegistryPostProcessor并模仿ConfigurationClassPostProcessor:
使用具有属性的声明类迭代 bean 注册表以获取 bean 定义,ComponentScan
例如(从ConfigurationClassPostProcessor
. 中提取):
public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) {
List<BeanDefinitionHolder> configCandidates = new ArrayList<BeanDefinitionHolder>();
String[] candidateNames = registry.getBeanDefinitionNames();
for (String beanName : candidateNames) {
if (ConfigurationClassUtils.checkConfigurationClassCandidate(beanDef, this.metadataReaderFactory)) {
// Extract component scan
}
}
}
像 Spring 一样提取这些属性
Set<AnnotationAttributes> componentScans = AnnotationConfigUtils.attributesForRepeatable(
sourceClass.getMetadata(), ComponentScans.class, ComponentScan.class);
然后像第一个解决方案一样扫描包并注册bean定义