点此返回
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
| public class AtBeanPostProcessor implements BeanFactoryPostProcessor { @Override public void postProcessBeanFactory (ConfigurableListableBeanFactory configurableListableBeanFactory) throws BeansException { try { CachingMetadataReaderFactory factory = new CachingMetadataReaderFactory(); MetadataReader reader = factory .getMetadataReader(new ClassPathResource("com/itheima/a05/Config.class")); Set<MethodMetadata> methods = reader .getAnnotationMetadata() .getAnnotatedMethods(Bean.class.getName());
for (MethodMetadata method : methods) { System.out.println(method); String initMethod = (String) method.getAnnotationAttributes(Bean.class.getName()).get("initMethod"); BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(); builder.setFactoryMethodOnBean(method.getMethodName(),"config"); builder.setAutowireMode(AbstractBeanDefinition.AUTOWIRE_CONSTRUCTOR); if (initMethod.length() > 0){ builder.setInitMethodName(initMethod); } AbstractBeanDefinition bd = builder.getBeanDefinition(); if (configurableListableBeanFactory instanceof DefaultListableBeanFactory beanFactory) { beanFactory.registerBeanDefinition(method.getMethodName(),bd); } } } catch (IOException e) { e.printStackTrace(); } } }
|
当其他类调用时,只需调用容器的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(AtBeanPostProcessor.class);
context.refresh(); for (String name : context.getBeanDefinitionNames()) { System.out.println(name); } context.close(); } }
|