美文网首页我爱编程
spring笔记-HierarchicalBeanFactory

spring笔记-HierarchicalBeanFactory

作者: 兴浩 | 来源:发表于2018-06-11 10:54 被阅读112次

BeanFactory分层

package org.springframework.beans.factory;
 //分层工厂
public interface HierarchicalBeanFactory extends BeanFactory {

     //返回工厂的父工厂
    BeanFactory getParentBeanFactory();

     //这个工厂中是否包含这个Bean
    boolean containsLocalBean(String name);
}

测试代码

    @Test
    public void testAutowireWithParent() throws Exception {
        DefaultListableBeanFactory xbf = new DefaultListableBeanFactory();
        new XmlBeanDefinitionReader(xbf).loadBeanDefinitions(AUTOWIRE_CONTEXT);
        DefaultListableBeanFactory lbf = new DefaultListableBeanFactory();
        MutablePropertyValues pvs = new MutablePropertyValues();
        pvs.add("name", "kerry");
        RootBeanDefinition bd = new RootBeanDefinition(TestBean.class);
        bd.setPropertyValues(pvs);
        lbf.registerBeanDefinition("spouse", bd);
        xbf.setParentBeanFactory(lbf);
        doTestAutowire(xbf);
    }

    private void doTestAutowire(DefaultListableBeanFactory xbf) throws Exception {
        DependenciesBean rod1 = (DependenciesBean) xbf.getBean("rod1");
        TestBean kerry = (TestBean) xbf.getBean("spouse");
        // should have been autowired
        assertEquals(kerry, rod1.getSpouse());
    }

调用了setParentBeanFactory设置BeanFactory,lbf中注册了spouse,所以在调用getBean时可以获取到spouse

参考:
http://www.bubuko.com/infodetail-2044144.html

相关文章

网友评论

    本文标题:spring笔记-HierarchicalBeanFactory

    本文链接:https://www.haomeiwen.com/subject/dwbceftx.html