Spring依赖注入

无论是基于注解的ApplicationContext(org.springframework.context.annotation.AnnotationConfigApplicationContext)

还是基于XML的ApplicationContext(org.springframework.context.support.ClassPathXmlApplicationContext)

它们在启动过程中都会调用org.springframework.context.support.AbstractApplicationContext#refresh方法

实例化Spring容器的核心方法是org.springframework.context.support.AbstractApplicationContext#refresh

在这个refresh方法中会获取BeanFactory,默认的BeanFactory是org.springframework.beans.factory.support.DefaultListableBeanFactory

 

在AbstractApplicationContext#refresh()方法的最后会实例化容器中所有非懒加载的单例bean,它是通过调用getBean()方法来做的,下面从getBean()开始分析

getBean方法是在AbstractBeanFactory中定义的,而所有的getBean方法最终都是调的doGetBean方法

 

AbstractBeanFactory#getBean

1、调用doGetBean方法

AbstractBeanFactory#doGetBean

1、检查singleton缓存中是否有这个bean,如果有直接返回

2、检查父级BeanFactory中是否有这个bean,如果有直接返回

3、检查这个BeanDefinition是否有依赖,如果有,则递归的获取这些依赖的bean(PS:通过getBean方法)直到没有依赖为止

4、通过createBean方法创建bean

AbstractAutowireCapableBeanFactory#createBean

1、如果设置了BeanPostProcessor,则返回一个代理对象

2、调用doCreateBean方法

AbstractAutowireCapableBeanFactory#doCreateBean

在这个方法中调用了两个特别重要的方法createBeanInstance和populateBean,前者用于实例化Bean,后者用于初始化Bean实例

org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#createBeanInstance

1、如果指定了工厂方法的话,则用指定的工厂方法实例化Bean

2、如果构造函数使用了自动装配的话,则使用autowireConstructor实例化Bean

3、决定以使用带参数的构造方法实例化Bean

4、使用默认的构造方法实例化Bean

补充:

1、autowire constructor

2、用默认的构造方法实例化的时候涉及到实例化策略,默认的策略是使用cglib,还有一种是使用反射

org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#populateBean

这一步所做的事情就是找到那些需要注入的属性和它所对应的实例,然后将它设置到相应的属性上

还有一点是属性的类型可能有多种,每一种的取值方式都不一样

 参考 

http://blog.csdn.net/hotdust/article/details/52613221

http://blog.csdn.net/lisongjia123/article/details/52134396

posted @ 2018-02-03 22:48  废物大师兄  阅读(882)  评论(0编辑  收藏  举报