点此返回
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
| public class MapperPostProcessor implements BeanDefinitionRegistryPostProcessor { @Override public void postProcessBeanDefinitionRegistry (BeanDefinitionRegistry beanFactory) throws BeansException { try { PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(); Resource[] resources = resolver .getResources("classpath:com/itheima/a05/mapper/**/*.class");
AnnotationBeanNameGenerator generator = new AnnotationBeanNameGenerator();
CachingMetadataReaderFactory factory = new CachingMetadataReaderFactory(); for (Resource resource : resources) { MetadataReader reader = factory.getMetadataReader(resource); ClassMetadata classMetadata = reader.getClassMetadata(); if (classMetadata.isInterface()) { AbstractBeanDefinition bd1 = BeanDefinitionBuilder .genericBeanDefinition(MapperFactoryBean.class) .addConstructorArgValue(classMetadata.getClassName()) .setAutowireMode(AbstractBeanDefinition.AUTOWIRE_BY_TYPE) .getBeanDefinition(); AbstractBeanDefinition bd2 = BeanDefinitionBuilder .genericBeanDefinition(classMetadata.getClassName()) .getBeanDefinition(); String beanName = generator.generateBeanName(bd2, beanFactory);
beanFactory.registerBeanDefinition(beanName,bd1); } } } catch (IOException e) { e.printStackTrace(); } }
@Override public void postProcessBeanFactory (ConfigurableListableBeanFactory beanFactory) throws BeansException { } }
|
当其他类调用时,只需调用容器的registerBean方法,传入对实现类.class文件即可
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| public class BeanApp { private static final Logger log = LoggerFactory.getLogger(BeanApp.class); public static void main(String[] args) throws IOException { GenericApplicationContext context = new GenericApplicationContext(); context.registerBean("config", Config.class);
context.registerBean(MapperPostProcessor.class);
context.refresh(); for (String name : context.getBeanDefinitionNames()) { System.out.println(name); } context.close(); } }
|