主要的问题

1. 什么是父子容器?

2. 为什么需要用父子容器?

3. 父子容器如何使用?

下面我们就来探讨探讨。

我们先来看一个案例

系统中有2个模块:module1和module2,两个模块是独立开发的,module2会使用到module1中的一些类,module1会将自己打包为jar提供给module2使用,我们来看一下这2个模块的代码。

模块1

放在module1包中,有3个类

Service1

package com.javacode2018.lesson002.demo17.module1;import org.springframework.stereotype.Component;@Component
public class Service1 {public String m1() {return "我是module1中的Servce1中的m1方法";}
}

Service2

package com.javacode2018.lesson002.demo17.module1;import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;@Component
public class Service2 {@Autowiredprivate com.javacode2018.lesson002.demo17.module1.Service1 service1; //@1public String m1() { //@2return this.service1.m1();}}

上面2个类,都标注了@Compontent注解,会被spring注册到容器中。

@1:Service2中需要用到Service1,标注了@Autowired注解,会通过spring容器注入进来

@2:Service2中有个m1方法,内部会调用service的m1方法。

来个spring配置类:Module1Config

package com.javacode2018.lesson002.demo17.module1;import org.springframework.context.annotation.ComponentScan;@ComponentScan
public class Module1Config {
}

上面使用了@CompontentScan注解,会自动扫描当前类所在的包中的所有类,将标注有@Compontent注解的类注册到spring容器,即Service1和Service2会被注册到spring容器。

再来看模块2

放在module2包中,也是有3个类,和模块1中的有点类似。

Service1

模块2中也定义了一个Service1,内部提供了一个m2方法,如下:

package com.javacode2018.lesson002.demo17.module2;import org.springframework.stereotype.Component;@Component
public class Service1 {public String m2() {return "我是module2中的Servce1中的m2方法";}
}

Service3

package com.javacode2018.lesson002.demo17.module2;import com.javacode2018.lesson002.demo17.module1.Service2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;@Component
public class Service3 {//使用模块2中的Service1@Autowiredprivate com.javacode2018.lesson002.demo17.module2.Service1 service1; //@1//使用模块1中的Service2@Autowiredprivate com.javacode2018.lesson002.demo17.module1.Service2 service2; //@2public String m1() {return this.service2.m1();}public String m2() {return this.service1.m2();}}

@1:使用module2中的Service1

@2:使用module1中的Service2

先来思考一个问题

上面的这些类使用spring来操作会不会有问题?会有什么问题?

这个问题还是比较简单的,大部分人都可以看出来,会报错,因为两个模块中都有Service1,被注册到spring容器的时候,bean名称会冲突,导致注册失败。

来个测试类,看一下效果

package com.javacode2018.lesson002.demo17;import com.javacode2018.lesson001.demo21.Config;
import com.javacode2018.lesson002.demo17.module1.Module1Config;
import com.javacode2018.lesson002.demo17.module2.Module2Config;
import org.junit.Test;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;public class ParentFactoryTest {@Testpublic void test1() {//定义容器AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();//注册beancontext.register(Module1Config.class, Module2Config.class); //@1//启动容器context.refresh();}
}

@1:将Module1Config、Module2Config注册到容器,spring内部会自动解析这两个类上面的注解,即:@CompontentScan注解,然后会进行包扫描,将标注了@Compontent的类注册到spring容器。

运行test1输出

下面是部分输出:

Caused by: org.springframework.context.annotation.ConflictingBeanDefinitionException: Annotation-specified bean name 'service1' for bean class [com.javacode2018.lesson002.demo17.module2.Service1] conflicts with existing, non-compatible bean definition of same name and class [com.javacode2018.lesson002.demo17.module1.Service1]

service1这个bean的名称冲突了。

那么我们如何解决?

对module1中的Service1进行修改?这个估计是行不通的,module1是别人以jar的方式提供给我们的,源码我们是无法修改的。

而module2是我们自己的开发的,里面的东西我们可以随意调整,那么我们可以去修改一下module2中的Service1,可以修改一下类名,或者修改一下这个bean的名称,此时是可以解决问题的。

不过大家有没有想过一个问题:如果我们的模块中有很多类都出现了这种问题,此时我们一个个去重构,还是比较痛苦的,并且代码重构之后,还涉及到重新测试的问题,工作量也是蛮大的,这些都是风险。

而spring中的父子容器就可以很好的解决上面这种问题。

什么是父子容器

创建spring容器的时候,可以给当前容器指定一个父容器。

BeanFactory的方式

//创建父容器parentFactory
DefaultListableBeanFactory parentFactory = new DefaultListableBeanFactory();
//创建一个子容器childFactory
DefaultListableBeanFactory childFactory = new DefaultListableBeanFactory();
//调用setParentBeanFactory指定父容器
childFactory.setParentBeanFactory(parentFactory);

ApplicationContext的方式

//创建父容器
AnnotationConfigApplicationContext parentContext = new AnnotationConfigApplicationContext();
//启动父容器
parentContext.refresh();//创建子容器
AnnotationConfigApplicationContext childContext = new AnnotationConfigApplicationContext();
//给子容器设置父容器
childContext.setParent(parentContext);
//启动子容器
childContext.refresh();

上面代码还是比较简单的,大家都可以看懂。

我们需要了解父子容器的特点,这些是比较关键的,如下。

父子容器特点

1. 父容器和子容器是相互隔离的,他们内部可以存在名称相同的bean

2. 子容器可以访问父容器中的bean,而父容器不能访问子容器中的bean

3. 调用子容器的getBean方法获取bean的时候,会沿着当前容器开始向上面的容器进行查找,直到找到对应的bean为止

4. 子容器中可以通过任何注入方式注入父容器中的bean,而父容器中是无法注入子容器中的bean,原因是第2点

使用父子容器解决开头的问题

关键代码

@Test
public void test2() {//创建父容器AnnotationConfigApplicationContext parentContext = new AnnotationConfigApplicationContext();//向父容器中注册Module1Config配置类parentContext.register(Module1Config.class);//启动父容器parentContext.refresh();//创建子容器AnnotationConfigApplicationContext childContext = new AnnotationConfigApplicationContext();//向子容器中注册Module2Config配置类childContext.register(Module2Config.class);//给子容器设置父容器childContext.setParent(parentContext);//启动子容器childContext.refresh();//从子容器中获取Service3Service3 service3 = childContext.getBean(Service3.class);System.out.println(service3.m1());System.out.println(service3.m2());
}

运行输出

我是module1中的Servce1中的m1方法
我是module2中的Servce1中的m2方法

这次正常了。

父子容器使用注意点

我们使用容器的过程中,经常会使用到的一些方法,这些方法通常会在下面的两个接口中

org.springframework.beans.factory.BeanFactory
org.springframework.beans.factory.ListableBeanFactory

这两个接口中有很多方法,这里就不列出来了,大家可以去看一下源码,这里要说的是使用父子容器的时候,有些需要注意的地方。

BeanFactory接口,是spring容器的顶层接口,这个接口中的方法是支持容器嵌套结构查找的,比如我们常用的getBean方法,就是这个接口中定义的,调用getBean方法的时候,会从沿着当前容器向上查找,直到找到满足条件的bean为止。

而ListableBeanFactory这个接口中的方法是不支持容器嵌套结构查找的,比如下面这个方法

String[] getBeanNamesForType(@Nullable Class<?> type)

获取指定类型的所有bean名称,调用这个方法的时候只会返回当前容器中符合条件的bean,而不会去递归查找其父容器中的bean。

来看一下案例代码,感受一下:

@Test
public void test3() {//创建父容器parentFactoryDefaultListableBeanFactory parentFactory = new DefaultListableBeanFactory();//向父容器parentFactory注册一个bean[userName->"路人甲Java"]parentFactory.registerBeanDefinition("userName",BeanDefinitionBuilder.genericBeanDefinition(String.class).addConstructorArgValue("路人甲Java").getBeanDefinition());//创建一个子容器childFactoryDefaultListableBeanFactory childFactory = new DefaultListableBeanFactory();//调用setParentBeanFactory指定父容器childFactory.setParentBeanFactory(parentFactory);//向子容器parentFactory注册一个bean[address->"上海"]childFactory.registerBeanDefinition("address",BeanDefinitionBuilder.genericBeanDefinition(String.class).addConstructorArgValue("上海").getBeanDefinition());System.out.println("获取bean【userName】:" + childFactory.getBean("userName"));//@1System.out.println(Arrays.asList(childFactory.getBeanNamesForType(String.class))); //@2
}

上面定义了2个容器

父容器:parentFactory,内部定义了一个String类型的bean:userName->路人甲Java

子容器:childFactory,内部也定义了一个String类型的bean:address->上海

@1:调用子容器的getBean方法,获取名称为userName的bean,userName这个bean是在父容器中定义的,而getBean方法是BeanFactory接口中定义的,支持容器层次查找,所以getBean是可以找到userName这个bean的

@2:调用子容器的getBeanNamesForType方法,获取所有String类型的bean名称,而getBeanNamesForType方法是ListableBeanFactory接口中定义的,这个接口中方法不支持层次查找,只会在当前容器中查找,所以这个方法只会返回子容器的address

我们来运行一下看看效果:

获取bean【userName】:路人甲Java
[address]

结果和分析的一致。

那么问题来了:有没有方式解决ListableBeanFactory接口不支持层次查找的问题?

spring中有个工具类就是解决这个问题的,如下:

org.springframework.beans.factory.BeanFactoryUtils

这个类中提供了很多静态方法,有很多支持层次查找的方法,源码你们可以去细看一下,名称中包含有Ancestors的都是支持层次查找的。

在test2方法中加入下面的代码:

//层次查找所有符合类型的bean名称
String[] beanNamesForTypeIncludingAncestors = BeanFactoryUtils.beanNamesForTypeIncludingAncestors(childFactory, String.class);
System.out.println(Arrays.asList(beanNamesForTypeIncludingAncestors));Map<String, String> beansOfTypeIncludingAncestors = BeanFactoryUtils.beansOfTypeIncludingAncestors(childFactory, String.class);
System.out.println(Arrays.asList(beansOfTypeIncludingAncestors));

运行输出

[address, userName]
[{address=上海, userName=路人甲Java}]

查找过程是按照层次查找所有满足条件的bean。

回头看一下springmvc父子容器的问题

问题1:springmvc中只使用一个容器是否可以?

只使用一个容器是可以正常运行的。

问题2:那么springmvc中为什么需要用到父子容器?

通常我们使用springmvc的时候,采用3层结构,controller层,service层,dao层;父容器中会包含dao层和service层,而子容器中包含的只有controller层;这2个容器组成了父子容器的关系,controller层通常会注入service层的bean。

采用父子容器可以避免有些人在service层去注入controller层的bean,导致整个依赖层次是比较混乱的。

父容器和子容器的需求也是不一样的,比如父容器中需要有事务的支持,会注入一些支持事务的扩展组件,而子容器中controller完全用不到这些,对这些并不关心,子容器中需要注入一下springmvc相关的bean,而这些bean父容器中同样是不会用到的,也是不关心一些东西,将这些相互不关心的东西隔开,可以有效的避免一些不必要的错误,而父子容器加载的速度也会快一些。

总结

1. 本文需掌握父子容器的用法,了解父子容器的特点:子容器可以访问父容器中bean,父容器无法访问子容器中的bean

2. BeanFactory接口支持层次查找

3. ListableBeanFactory接口不支持层次查找

4. BeanFactoryUtils工具类中提供了一些非常实用的方法,比如支持bean层次查找的方法等等

案例源码

https://gitee.com/javacode2018/spring-series

Spring第24篇:父子容器详解相关推荐

  1. Spring系列:父子容器详解

    又一次被面试官带到坑里面了. 面试官:springmvc用过么? 我:用过啊,经常用呢 面试官:springmvc中为什么需要用父子容器? 我:嗯...没听明白你说的什么. 面试官:就是control ...

  2. Spring父子容器详解!!!!

    访问规则:子容器可以访问父容器的对象,父容器不能访问子容器的对象 1.ContextLoaderListener会被优先初始化时,其会根据元素中contextConfigLocation参数指定的配置 ...

  3. Spring第38篇:定时器详解(@Scheduled @EnableScheduling)

    Spring中 @Scheduled & @EnableScheduling 这2个注解,可以用来快速开发定时器,使用特别的简单. 如何使用? 用法 1.需要定时执行的方法上加上@Schedu ...

  4. spring之旅第四篇-注解配置详解

    spring之旅第四篇-注解配置详解 一.引言 最近因为找工作,导致很长时间没有更新,找工作的时候你会明白浪费的时间后面都是要还的,现在的每一点努力,将来也会给你回报的,但行好事,莫问前程!努力总不会 ...

  5. Spring生命周期Bean初始化过程详解

    Spring生命周期Bean初始化过程详解 Spring 容器初始化 Spring Bean初始化 BeanFactory和FactoryBean 源码分析 Bean的实例化 preInstantia ...

  6. Spring AOP 增强框架 Nepxion Matrix 详解

    点击上方"方志朋",选择"置顶或者星标" 你的关注意义重大! 概述 在<深入聊一聊 Spring AOP 实现机制>一文中,介绍了 Spring A ...

  7. STL 之 deque容器详解

    Deque 容器 deque容器是C++标准模版库(STL,Standard Template Library)中的部分内容.deque容器类与vector类似,支持随机访问和快速插入删除,它在容器中 ...

  8. STL 之 list 容器详解

    STL之list容器详解 List 容器 list是C++标准模版库(STL,Standard Template Library)中的部分内容.实际上,list容器就是一个双向链表,可以高效地进行插入 ...

  9. spring aop实例讲解_Spring核心技术详解(一)

    一.Sring简介 Spring是一个分层的Java SE/EE应用一站式的轻量级开源框架.Spring核心是IOC和AOP. Spring主要优点包括: 方便解耦,简化开发,通过Spring提供的I ...

最新文章

  1. nginx.pid failed (2: The system cannot find the file specified
  2. 【测试】SAP 委外加工收货BAPI Demo
  3. amazon linux 安装nginx,linux – NGINX不显示Amazon EC2实例上的默认页...
  4. LiveMigration之四配置高可用虚拟机
  5. linux系统指令学习
  6. 七十四、SpringBoot 的数据缓存cache(一)
  7. 【JFreeChart】JFreeChart—输出组合图表
  8. 完美图解教程 Linux环境VNC服务安装、配置与使用
  9. Python 第一篇:python简介和入门
  10. Javamysql语法转化oracle_MySQL与Oracle的语法区别详细对比
  11. Monocular slam 中的理论基础(2)
  12. 什么是网点?印刷网点与CMYK色彩,彩色渐变色印刷原理。
  13. Nginx nginx.conf配置文件详解
  14. 【解决方案】“博物馆热”背后,如何建设安防视频监控体系保障文物安全?
  15. 搭建属于自己的数字IC EDA环境(六):开机自动激活 Synopsys license
  16. Win10 tensorflow 1.12 gpu + CUDA10 + Anaconda3-4.4 python3.6 安装过程
  17. XAMPP介绍、安装及使用
  18. 计算机弹歌光年之外谱子,邓紫棋《光年之外》完整钢琴谱
  19. 基于stm32的智能小车设计(一)
  20. Dockerfile自定义镜像

热门文章

  1. 如何画QQ-plot
  2. mini2440 u-boot-2009.03 移植最详细攻略
  3. 什么是__proto__和prototype
  4. 创意字体设计欣赏和案例教程:火、烟、水、冰、霜特效
  5. php网站系统说明,PHPWEB软件文件系统结构说明
  6. 【Error】解决curl: command not found
  7. 计算机基础开学考试试卷,计算机应用基础试卷试题及答案.doc
  8. 一包烟尝试解决docx安装失败,并尝试运行标号、全文格式、生成表格自动化处理(2)
  9. ------------------------重阳节随笔--------------------------
  10. Eggs Dropping puzzle(2 eggs, 100 floors)