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
    }
}
相關文章
相關標籤/搜索