You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1.9 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

一、什么是父子容器

创建Spring容器的时候可以给当前容器指定一个父容器。用于解决bean冲突问题

父容器特点

  1. 父容器和子容器是相互隔离的内部可以存在名称相同的Bean
  2. 子容器可以访问父容器中的Bean,而父容器不能访问子容器中的Bean
  3. 调用子容器的getBean方法获取bean的时候会沿着当前容器开始向上面的容器进行查找直到找到对应的bean为止
  4. 子容器中可以通过任何注入方式注入父容器中的bean而父容器中是无法注入子容器中的bean

创建子容器

!Snipaste_2023-02-16_16-04-16 4.png

父子容器使用注意点

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

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

二、常见问题

1.springmvc中只使用一个容器是否可以

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

2.springmvc中为什么需要用到父子容器

  1. mvc采用3层架构其中父容器会包含dao层和service层而子容器中只有controller层,采用父子容器可以避免有些人在service层注入controller层的Bean导致依赖层次混乱。
  2. 父子容器需求不一样父容器区中需要事务支持会注入一些支持事务的扩展组件而子容器中controller不需要。综上父子容器可以将相互不关心的东西进行隔离可以有效的避免一些不要的错误而父子容器加载的速度也会快一些。