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>
  • 相关阅读:
    呈现系统-组件间的通信方式(7)
    web项目中图标的前端处理方案
    ADO--数据访问技术
    canvas--绘制路径
    canvas--改变颜色
    canvas-在画布中画两个方块(一个空心一个实体)
    canvas--画布《第一步》
    拼图游戏【简单】
    判断字符串是否为空--string.Empty、string=""、s.length==0
    判断Char是否为数字
  • 原文地址:https://www.cnblogs.com/atai/p/7658850.html
Copyright © 2011-2022 走看看