Spring 双亲容器
2016-05-15 11:18
399 查看
应用场景
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>
相关文章推荐
- java库中的具体的集合
- myeclipse编辑xml文件的显示格式问题
- java Executor 提供的五种线程池
- Java并发编程(1)一基础类和接口
- 如何利用jdk来把java文件变成.c
- Axis2开发webservice案例详解
- eclipse 常用快捷键
- Spring Mvc ajax和json数据格式的配置
- Java基础 封装
- spring mvc 任务定时器 @Scheduled
- java Base64加密实现
- Java中普通代码块,构造代码块,静态代码块区别及代码示例
- java设计模式:单例设计模式
- Spring MVC 的请求过程
- dom4j解析spring.xml 对象解析(二)
- Eclipse 集成 git 的使用手册
- JNI中的使用把java中字符串转变为c中char*
- 浅析Java内存模型与垃圾回收
- 初识 java 反射机制 (二)
- Java OCR tesseract 图像智能字符识别技术