BeanFactory父子容器的知識


容器知識點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
    }
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM