spring笔记-BeanDefinitionReader

1.概念 【spring笔记-BeanDefinitionReader】BeanDefinitionReader用于加载Bean,常规用到最多的就是bean的xml配置
spring笔记-BeanDefinitionReader
文章图片
2.示例 XmlBeanDefinitionReader需要传入一个BeanDefinitionRegistry实例,并调用loadBeanDefinitions方法加载一个xml文件的Resource资源
loadBeanDefinitions调用结束后xml中声明的bean就会注册到BeanDefinitionRegistry中

@Test public void test() { SimpleBeanDefinitionRegistry registry = new SimpleBeanDefinitionRegistry(); Resource resource = new InputStreamResource(getClass().getResourceAsStream("test.xml")); XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(registry); reader.loadBeanDefinitions(resource); testBeanDefinitions(registry); }

3.根据XmlBeanDefinitionReader来创建BeanFactory
protected BeanFactory createDefinition(String resourceLocation) { DefaultListableBeanFactory factory = new DefaultListableBeanFactory(); XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(factory); ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver(); try { Resource[] configResources = resourcePatternResolver.getResources(resourceLocation); reader.loadBeanDefinitions(configResources); } catch (IOException ex) { throw new BeanDefinitionStoreException( "Error accessing bean definition resource [" + this.resourceLocation + "]", ex); } catch (BeanDefinitionStoreException ex) { throw new FatalBeanException("Unable to load group definition: " + "group resource name [" + this.resourceLocation + "]", ex); }return factory; }

参考文章:
Spring Bean 加载 - BeanDefinitionReader

    推荐阅读