《深入浅出Spring》父子容器

本文介绍了Spring框架中的父子容器概念,包括BeanFactory和ApplicationContext创建父子容器的方式。父子容器的特点是内部相互隔离,子容器能访问父容器的bean,反之不行。文章通过实例展示了模块间的bean冲突问题以及如何利用父子容器解决。还提到了BeanFactory接口支持层次查找,而ListableBeanFactory不支持,但可通过BeanFactoryUtils工具类实现。最后讨论了SpringMVC中使用父子容器的原因和优势。

什么是父子容器

创建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点

栗子:

模块1

@Component
public class Service1 {
   
   
    public String m1() {
   
   
        return "我是module1中的Servce1中的m1方法";
    }
}
@Component
public class Service2 {
   
   

    @Autowired
    private Service1 service1; //@1
    public String m1() {
   
    //@2
        return this.service1.m1();
    }
}

上面2个类,都标注了@Compontent注解,会被spring注册到容器中。
@1:Service2中需要用到Service1,标注了@Autowired注解,会通过spring容器注入进来
@2:Service2中有个m1方法,内部会调用service的m1方法。

@ComponentScan
public class Module1Config {
   
   
}

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

模块2

@Component
public class Service1 {
   
   
    public String m2() {
   
   
        return "我是module2中的Servce1中的m2方法";
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值