点此返回
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
|
public class ComponentScanPostProcessor implements BeanDefinitionRegistryPostProcessor { @Override public void postProcessBeanFactory (ConfigurableListableBeanFactory configurableListableBeanFactory) throws BeansException { try { ComponentScan componentScan = AnnotationUtils .findAnnotation(Config.class, ComponentScan.class); if (componentScan != null) { for (String p : componentScan.basePackages()) { String path = "classpath*:" + p.replace(".", "/") + "/**/*.class"; CachingMetadataReaderFactory factory = new CachingMetadataReaderFactory(); Resource[] resources = new PathMatchingResourcePatternResolver().getResources(path); AnnotationBeanNameGenerator generator = new AnnotationBeanNameGenerator(); for (Resource resource : resources) { MetadataReader reader = factory.getMetadataReader(resource); if (reader.getAnnotationMetadata() .hasMetaAnnotation(Component.class.getName()) || reader.getAnnotationMetadata() .hasAnnotation(Component.class.getName())) { AbstractBeanDefinition bd = BeanDefinitionBuilder .genericBeanDefinition(reader .getClassMetadata() .getClassName()) .getBeanDefinition(); if (configurableListableBeanFactory instanceof DefaultListableBeanFactory beanFactory) { String beanName = generator.generateBeanName(bd, beanFactory); beanFactory.registerBeanDefinition(beanName,bd); } } } } } } catch (IOException e) { e.printStackTrace(); } } }
|
当其他类使用时,只需要调用 context的 registerBean方法,并传入自定义类的.class即可
1 2 3 4 5 6 7 8 9
| GenericApplicationContext context = new GenericApplicationContext(); context.registerBean(ComponentScanPostProcessor.class);
context.refresh();
context.close();
|