• [转]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>
  • 相关阅读:
    django继承User表导致的问题
    Sublime Text 3 鼠标右键快捷选项 简单且高效
    php所有版本
    windows 安装redis
    php玩弄redis基本操作
    PHP 实现文件下载
    PHP 获取客户端的真实IP
    根据标签内个数,显示隐藏《加载更多》
    ubuntu 安装nginx+php+mysql+phpadmin环境
    面试总结
  • 原文地址:https://www.cnblogs.com/atai/p/7658850.html
Copyright © 2020-2023  润新知