BeanFactory父子容器的知识

Spring父子容器详解

容器知识点1:

在Spring中,关于父子容器相关的接口HierarchicalBeanFactory,以下是该接口的代码:

public interface HierarchicalBeanFactory extends BeanFactory {
    BeanFactory getParentBeanFactory();    //返回本Bean工厂的父工厂
    boolean containsLocalBean(String name); //本地工厂是否包含这个Bean
}

其中:

  1、第一个方法getParentBeanFactory(),返回本Bean工厂的父工厂。这个方法实现了工厂的分层。

  2、第二个方法containsLocalBean(),判断本地工厂是否包含这个Bean(忽略其他所有父工厂)。

以下会举例介绍该接口在实际实践中应用:

  (1)、定义一个Person类:

class Person {
    private int age;
    private String name;
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
}

(2)、首先需要定义两个容器定义的xml文件

 childXml.xml:
 

<bean id="child" class="com.spring.hierarchical.Person">
        <property name="age" value= "11"></property>
        <property name="name" value="erzi"></property>
    </bean>

parentXml.xml:

<bean id="parent" class="com.spring.hierarchical.Person">
        <property name="age" value= "50"></property>
        <property name="name" value="baba"></property>
    </bean>

(3)、写测试代码:
 

public class Test {
    public static void main(String[] args) {
        //父容器
        ApplicationContext parent = new ClassPathXmlApplicationContext("parentXml.xml");
        //子容器,在构造方法中指定
        ApplicationContext child = new ClassPathXmlApplicationContext(new String[]{"childXml.xml"},parent);
        
        System.out.println(child.containsBean("child"));  //子容器中可以获取Bean:child
        System.out.println(parent.containsBean("child")); //父容器中不可以获取Bean:child
        System.out.println(child.containsBean("parent")); //子容器中可以获取Bean:parent
        System.out.println(parent.containsBean("parent")); //父容器可以获取Bean:parent
        //以下是使用HierarchicalBeanFactory接口中的方法
        ApplicationContext parent2 = (ApplicationContext) child.getParentBeanFactory();  //获取当前接口的父容器
        System.out.println(parent == parent2);
        System.out.println(child.containsLocalBean("child"));  //当前子容器本地是包含child
        System.out.println(parent.containsLocalBean("child")); //当前父容器本地不包含child
        System.out.println(child.containsLocalBean("parent")); //当前子容器本地不包含child
        System.out.println(parent.containsLocalBean("parent")); //当前父容器本地包含parent
    }
}

 

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值