BeanFactory父子容器的知识

容器知识点1:spring

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

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

其中:this

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

  二、第二个方法containsLocalBean(),判断本地工厂是否包含这个Bean(忽略其余全部父工厂)。code

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

  (1)、定义一个Person类:blog

      

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:get

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

parentXml.xml:io

<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
    }
}
相关文章
相关标签/搜索