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
原理
调用链路:getBean
→getBeanFactory().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。