zoukankan      html  css  js  c++  java
  • [转]Spring IOC父子容器简介

    通过HierarchicalBeanFactory接口,Spring的IoC容器可以建立父子层级关联的容器体系,子容器可以访问父容器中的Bean,但父容器不能访问子容器的Bean。在容器内,Bean的id必须是唯一的,但子容器可以拥有一个和父容器id相同的Bean。父子容器层级体系增强了Spring容器架构的扩展性和灵活性,因为第三方可以通过编程的方式,为一个已经存在的容器添加一个或多个特殊用途的子容器,以提供一些额外的功能。 

    Spring使用父子容器实现了很多功能,比如在Spring MVC中,展现层Bean位于一个子容器中,而业务层和持久层的Bean位于父容器中。这样,展现层Bean就可以引用业务层和持久层的Bean,而业务层和持久层的Bean则看不到展现层的Bean。

    应用举例
    Runner.java

    //这个类负责启动父容器
    public class Runner {
        public static void main(String[] args){
            ApplicationContext context = new ClassPathXmlApplicationContext("classpath*:/spring1.xml");
        }
    }

    PluginLoader.java

    public class PluginLoader implements ApplicationContextAware {
        ApplicationContext parentApplicationContext;
        ConfigurableApplicationContext childContext;
    
        public void load() {
          //扫描所有classpath下面的以plugin_开头spring的配置文件进行装配,这里约定所有的子容器插件都必须有一个以plugin_开头的配置文件,并通过这个文件被父容器加载
            childContext = new ClassPathXmlApplicationContext("classpath*:/plugin_*.xml");
            childContext.setParent(parentApplicationContext);
            childContext.refresh();
        }
    
        public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
            this.parentApplicationContext = applicationContext;
        }
    }

    可以看到父容器(spring1.xml):

    <bean id="parentClass" class="com.test1.ParentClass"></bean>
    <bean id="pluginLoader" class="com.test1.PluginLoader" init-method="load"></bean>

    子容器(plugin_1.xml):

    <bean id="childContext1" class="com.test1.child.ChildContext1"></bean>
  • 相关阅读:
    js函数和变量的执行顺序【易错】
    JavaScript实现对象的深度克隆及typeof和instanceof【简洁】【分享】
    java数组与字符串相互转换、整型与字符串相互转换【详解】
    Math对象常用方法(取整细节)
    不使用临时变量互换两个变量的值
    python discover 函数介绍
    Appium+python 一个简单的登录测试实例
    IOS-优质应用推荐
    Appium+Python 自动化-appium常用元素定位方法
    Python+Selenium 自动化实现实例-单元测试报告
  • 原文地址:https://www.cnblogs.com/atai/p/7658850.html
Copyright © 2011-2022 走看看