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>
  • 相关阅读:
    java获取程序执行时间
    自己不去努力 还有谁能帮你
    错误: 找不到或无法加载主类 的解决办法
    不要迷信红黑树 哈希是一切
    nancy的诊断2
    nancy中的诊断功能面板1
    ironpython 2.75 在c#中的使用
    sqlserver2008创建数据库 报 Cannot read property is filestream 此属性不可用于sql server 7.0 解决
    结巴net 分词 配置文件路径,在网站中的出现问题的解决
    akka 练手 原来第一次是原封不动的返回传出去的参数
  • 原文地址:https://www.cnblogs.com/atai/p/7658850.html
Copyright © 2011-2022 走看看