攀登Spring珠穆朗玛峰:关于父子容器那些事儿

Spring的父子容器

特性

Spring 在ConfigurableApplicationContext中定义了setParent方法,这个方法是Spring用来实现父子容器关联的方法。简明扼要的说,Spring提供了父子容器设置的功能。先总结一下父子容器的特性。

  • 子容器可以获取父容器中的Bean
  • 父容器不可以获取子容器的Bean
  • 子容器与子容器之间相互隔离,互相不能获取;
  • 父子关系可以有多层,先从低级的开始获取,获取之后结束匹配;

案例测试

ps:注意两容器配置类上的@ComponentScan,最好将两容器各自加载的类分包存放,总之确保父子容器只加载自己的部分。

父容器相关定义

@Configuration
@ComponentScan("container.aparent")
public class AppConfigWithParent {
    
    @Bean(name = "parentPerson")
	public Person person(){
		return new Person("parent");
	}
}

@Component("parentHuman")
public class Human {	
	public void method(){
		System.out.println("parent human");
	}
}

子容器相关定义

@Configuration
@ComponentScan("container.child")
public class AppConfigWithChild {

   @Bean(name = "childPerson")
   public Person person() {
      return new Person("child");
   }
}

@Component("childMan")
public class Man {
	public void method(){
		System.out.println("child man");
	}
}

定义同时被父子容器注入的Person

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Person {
   private String name;

   public void method() {
      System.out.println(this.name);
   }
}

测试类以及结果

public class Test {
   static AnnotationConfigApplicationContext parentContext = new AnnotationConfigApplicationContext(AppConfigWithParent.class);
   static AnnotationConfigApplicationContext childContext;

   static {
      childContext = new AnnotationConfigApplicationContext();
      childContext.setParent(parentContext);
      childContext.register(AppConfigWithChild.class);
      childContext.refresh();
   }

   public static void main(String[] args) {
      parentContext.getBean(Human.class).method();
      parentContext.getBean(Person.class).method();

      System.out.println("------------");
	  
      childContext.getBean(Man.class).method();
      childContext.getBean(Person.class).method();
      childContext.getBean(Human.class).method();
       
      parentContext.getBean(Man.class).method();
   }
}
//      结果:如下
//		parent human
//		parent
//				------------
//		child man
//		child
//		parent human
//		Exception in thread "main" org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type //	   'container.child.Man' available

执行结果和特性描述一致:

  • 子容器不能获取到父容器的Man
  • 父子容器同时定义Bean时,优先获取本容器的Bean

原理

调用链路:getBeangetBeanFactory().getBean(requiredType)getBean(Class<T> requiredType, @Nullable Object... args)resolveBean(ResolvableType requiredType, @Nullable Object[] args, boolean nonUniqueAsNull)

resolveBean方法
@Nullable
private <T> T resolveBean(ResolvableType requiredType, @Nullable Object[] args, boolean nonUniqueAsNull) {
   NamedBeanHolder<T> namedBean = resolveNamedBean(requiredType, args, nonUniqueAsNull);
   if (namedBean != null) {
      return namedBean.getBeanInstance();
   }
   //如果需要获取的Bean在当前容器里面没有加载到,就去父容器里面加载
   BeanFactory parent = getParentBeanFactory();
   if (parent instanceof DefaultListableBeanFactory) {
      //不断递归找父容器的父容器,直到遍历完为止
      return ((DefaultListableBeanFactory) parent).resolveBean(requiredType, args, nonUniqueAsNull);
   }
   else if (parent != null) {
      ObjectProvider<T> parentProvider = parent.getBeanProvider(requiredType);
      if (args != null) {
         return parentProvider.getObject(args);
      }
      else {
         return (nonUniqueAsNull ? parentProvider.getIfUnique() : parentProvider.getIfAvailable());
      }
   }
   return null;
}

在这个方法里面可以看到,如果当前工厂里面没有获取到Bean,则从父工厂里面去获取,如果还是没有找到,从父容器的父容器开始找……

分别查看父子两个容器的单例池(SingletonObjects),也可以发现,他们只存了各自的Bean。子容器单例池也不会存父容器的内容。

获取到Bean之后停止查找,直接返回。

使用场景

其实关于使用和实现都没什么好说的,毕竟原理实在不能更简单了。更多的应该是从设计思路上面考虑它。

为什么要有父子容器?父子容器拿来干什么?

提一下SpringMVC和 Spring 的经典使用。

分层上的考虑
  • 从框架分层来考虑,传统的三层式架构是 Controller 调用 Service和 Dao;
  • 那么我们不应当在 Service和 Dao里面来注入 controller,这样就在使用上逻辑颠倒了;
  • 使用父子容器能根本上解决这个问题:将 Web 层(Controller)放在子容器,Service 和 Dao 放在父容器。
拓展上的考虑
  • Web 层的选型并不一定是 SpringMVC(当然我觉得其实也没啥选择了)
  • 以防万一,如果需要切换到 Struts2,修改相关的 Web 层配置即可。
需要注意的地方

如果使用 Spring+SpringMVC时,还参加了其他的框架,并且其他的框架有需要用到 Spring IOC 层面的Bean
比如需要在第三方框架里面调用某个service完成数据库操作。这时需要注意,第三方框架得要获取到父容器的引用。

进而引发ContextLoadListener作用的思考:

ContextLoadListener加载父容器初始化Spring IOC并存到全局对象ServletContext,那么其他框架也能借ServletContext获取父容器上下文。 (ps:方法getWebApplicationContext是静态的),进而第三方框架得以调用 Spring IOC。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值