基本步骤
- 定义一个注解
- 定义一个扫描规则
- 注入需要的元素
- 配置
定义注解
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface GodmeAnnotation {
}
扫描规则
public class Scanner extends ClassPathBeanDefinitionScanner {
public Scanner(BeanDefinitionRegistry registry) {
super(registry);
}
@Override
protected void registerDefaultFilters() {
addIncludeFilter(new AnnotationTypeFilter(GodmeAnnotation.class));
}
@Override
protected boolean isCandidateComponent(AnnotatedBeanDefinition beanDefinition) {
return super.isCandidateComponent(beanDefinition) && beanDefinition.getMetadata().hasAnnotation(GodmeAnnotation.class.getName());
}
@Override
protected Set<BeanDefinitionHolder> doScan(String... basePackages) {
Set<BeanDefinitionHolder> scanResult = super.doScan(basePackages);
scanResult.forEach(beanDefinitionHolder -> System.err.println(beanDefinitionHolder.getBeanDefinition().getBeanClassName()));
return scanResult;
}
}
组件补充
public class ScannerProcessor implements ApplicationContextAware, BeanFactoryPostProcessor {
private ApplicationContext context;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.context = applicationContext;
}
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory configurableListableBeanFactory) throws BeansException {
Scanner scanner = new Scanner((BeanDefinitionRegistry) configurableListableBeanFactory);
scanner.setResourceLoader(this.context);
scanner.scan("com.godme.spring.beans");
}
}
流程注入
@Configuration
public class Config {
@Bean
public BeanFactoryPostProcessor beanFactoryPostProcessor(){
return new ScannerProcessor();
}
}
效果验证
public class Starter {
public static void main(String[] args) {
AnnotationConfigApplicationContext configApplicationContext = new AnnotationConfigApplicationContext(Config.class);
Stream.of(configApplicationContext.getBeanDefinitionNames()).forEach(System.out::println);
}
}
小结