• 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
        }
    }
  • 相关阅读:
    10-关于DOM的事件操作
    09-伪数组 arguments
    08-函数
    07-常用内置对象
    Django -- 2.http协议
    Django -- 1.web应用
    web前端 --- JavaScrip之BOM
    web前端 --- JavaScrip函数与对象
    web前端 --- JavaScrip基础
    web前端 --- CSS下篇
  • 原文地址:https://www.cnblogs.com/mayang2465/p/12163179.html
Copyright © 2020-2023  润新知