Spring 双亲容器

来源:互联网 发布:高中数学算法初步教案 编辑:程序博客网 时间:2024/05/01 00:20

应用场景

Spring中父子容器的实现实例Spring的父子容器可以通过ConfigurableApplicationContext或ConfigurableBeanFactory来实现。

这两个接口中分别有setParent及setParentBeanFactory方法,可以与当前的子容器进行父子容器关联。

这个时候子容器就可以引用父容器中的bean,但是父容器是不能够引用子容器中的bean的,并且各个子容器中定义的bean是互不可见的,这样也可以避免因为不同的插件定义了相同的bean而带来的麻烦。

应用场景包括插件或组件的接入,只需要对方提供JAR即可,由父容器进行引导,各个子容器再完成自己的应该完成的工作即可。

应用举例

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)

<pre name="code" class="html"><bean id="childContext1" class="com.test1.child.ChildContext1"></bean>
0 0
原创粉丝点击