spring源码解析之IOC容器(三)——依赖注入
2020-12-13 03:55
标签:idt bst cleanup OLE src register 清除 抽象类 seq 上一篇主要是跟踪了IOC容器对bean标签进行解析之后存入Map中的过程,这些bean只是以BeanDefinition为载体单纯的存储起来了,并没有转换成一个个的对象,今天继续进行跟踪,看一看IOC容器是怎样实例化对象的。 我们都使用过以下代码: 这样我们就能获取到user对象了,所以,不难想象,这个getBean方法就是实例化对象的入口。接下来我们就以这个方法为切入点,来探究IOC容器中bean的实例化过程。getBean方法是在FileSystemXmlApplicationContext的基类AbstractApplicationContext中定义的,代码如下: 里面有很多重载方法,里面有调用了某个beanFactory的getBean方法。AbstractApplicationContext中并没有定义getBeanFactory这个方法,那一定是在FileSystemXmlApplicatio —ntext的某个父类中定义的,我们再回过头看一下它的UML图: 经过查找之后,是在AbstractRefreshableApplicationContext中定义的,且这个beanFactory是DefaultListableBeanFactory类型的: 直接进入DefaultListableBeanFactory中,查看它的getBean方法: 发现里面只有这两个重载方法,其他getBean方法,包括例子中使用的那个重载方法没有看到,我们看一下DefaultListableBeanFactory类的UML图:
经查找,发现在父类AbstractBeanFactory中定义了其他的getBean方法,如下: 里面都调用了doGetBean方法,那么进入继续跟踪: 可以看到对不同scope域的bean的创建过程,其中会进行递归创建,现在进入createBean方法中,其实现是在AbstractAutowireCapableBeanFactory类中,代码如下: 进入doCreateBean方法: 这里要说一下,当在创建bean时,IOC会将该bean的名字存一份到singletonsCurrentlyInCreation这个map中,然后每次创建的时候都会到里面进行检查当前bean是否正在被创建。为了避免发生循环引用(A依赖B,B依赖C,C依赖A)引起是循环,在第一次创建bean时,IOC容器会把用于创建这个bean的工厂对象放入singletonFactories这个map中,key是这个正在被创建的bean的名字。这样发生循环依赖的时候,就不再调用getBean方法了,而是直接使用工厂创建一个bean给被依赖的对象。比如第一次创建A时,将A的名称存入了singletonsCurrentlyInCreation这个map中,并且调用addSingletonFactory方法,将创建A的工厂放到singletonFactories中了,然后递归调用getBean创建依赖对象B、C,创建C时,要先创建它的依赖对象A,此时,IOC容器检查到singletonsCurrentlyInCreation中已经有这个A了,说明它已经在创建的过程中,只是还没有完成创建,此时,IOC容器直接就使用这个工厂将A创建出来赋给C了,然后再往回完成B和A的创建。可以看一下addSingletonFactory方法的实现: 在进行递归调用getBean方法创建依赖对象之前,getSignal方法是先调用的,前面的代码,doGetBean方法中可以看到,可以多看几遍就能理解。另外,对于原型实例,不允许循环引用。循环引用只针对单例。下一篇跟踪bean的属性的填充。 spring源码解析之IOC容器(三)——依赖注入 标签:idt bst cleanup OLE src register 清除 抽象类 seq 原文地址:https://www.cnblogs.com/helei123/p/11087463.html1 FileSystemXmlApplicationContext context=new FileSystemXmlApplicationContext("bean.xml");
2 User user=context.getBean("user",User.class);
1 public
1 public abstract class AbstractRefreshableApplicationContext extends AbstractApplicationContext {
2
3 private Boolean allowBeanDefinitionOverriding;
4
5 private Boolean allowCircularReferences;
6
7 /** Bean factory for this context */
8 private DefaultListableBeanFactory beanFactory;
9
10 /** Synchronization monitor for the internal BeanFactory */
11 private final Object beanFactoryMonitor = new Object();
public
public
1 public Object getBean(String name, Object... args) throws BeansException {
2 return doGetBean(name, null, args, false);
3 }
1 public
1 protected
1 protected Object createBean(String beanName, RootBeanDefinition mbd, Object[] args) throws BeanCreationException {
2 if (logger.isDebugEnabled()) {
3 logger.debug("Creating instance of bean ‘" + beanName + "‘");
4 }
5 RootBeanDefinition mbdToUse = mbd;
6
7 // Make sure bean class is actually resolved at this point, and
8 // clone the bean definition in case of a dynamically resolved Class
9 // which cannot be stored in the shared merged bean definition.
10 //判断需要创建的bean是否可以实例化,是否可以通过类装载其进行装载
11 Class> resolvedClass = resolveBeanClass(mbd, beanName);
12 if (resolvedClass != null && !mbd.hasBeanClass() && mbd.getBeanClassName() != null) {
13 mbdToUse = new RootBeanDefinition(mbd);
14 mbdToUse.setBeanClass(resolvedClass);
15 }
16
17 // Prepare method overrides.
18 try {
19 //这里是对overrides属性和look-up属性的处理
20 mbdToUse.prepareMethodOverrides();
21 }
22 catch (BeanDefinitionValidationException ex) {
23 throw new BeanDefinitionStoreException(mbdToUse.getResourceDescription(),
24 beanName, "Validation of method overrides failed", ex);
25 }
26
27 try {
28 //AOP就是这里操作的,如果配置了postProcessor,则生成一个proxy返回,即代理类
29 // Give BeanPostProcessors a chance to return a proxy instead of the target bean instance.
30 Object bean = resolveBeforeInstantiation(beanName, mbdToUse);
31 if (bean != null) {
32 return bean;
33 }
34 }
35 catch (Throwable ex) {
36 throw new BeanCreationException(mbdToUse.getResourceDescription(), beanName,
37 "BeanPostProcessor before instantiation of bean failed", ex);
38 }
39 //创建bean的方法调用
40 Object beanInstance = doCreateBean(beanName, mbdToUse, args);
41 if (logger.isDebugEnabled()) {
42 logger.debug("Finished creating instance of bean ‘" + beanName + "‘");
43 }
44 return beanInstance;
45 }
1 protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final Object[] args)
2 throws BeanCreationException {
3
4 // Instantiate the bean.
5 BeanWrapper instanceWrapper = null;
6 if (mbd.isSingleton()) {
7 //如果是单例,先把缓存中的同名Bean清除
8 instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);
9 }
10 //如果缓存中没有
11 if (instanceWrapper == null) {
12 //则创建一个实例
13 instanceWrapper = createBeanInstance(beanName, mbd, args);
14 }
15 final Object bean = (instanceWrapper != null ? instanceWrapper.getWrappedInstance() : null);
16 Class> beanType = (instanceWrapper != null ? instanceWrapper.getWrappedClass() : null);
17 mbd.resolvedTargetType = beanType;
18
19 // Allow post-processors to modify the merged bean definition.
20 synchronized (mbd.postProcessingLock) {
21 if (!mbd.postProcessed) {
22 try {
23 //使用后置处理器进行处理
24 applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);
25 }
26 catch (Throwable ex) {
27 throw new BeanCreationException(mbd.getResourceDescription(), beanName,
28 "Post-processing of merged bean definition failed", ex);
29 }
30 mbd.postProcessed = true;
31 }
32 }
33
34 // Eagerly cache singletons to be able to resolve circular references
35 // even when triggered by lifecycle interfaces like BeanFactoryAware.
36 //这里是对单例的循环引用的处理
37 boolean earlySingletonExposure = (mbd.isSingleton() && this.allowCircularReferences &&
38 isSingletonCurrentlyInCreation(beanName));
39 if (earlySingletonExposure) {
40 if (logger.isDebugEnabled()) {
41 logger.debug("Eagerly caching bean ‘" + beanName +
42 "‘ to allow for resolving potential circular references");
43 }
44 addSingletonFactory(beanName, new ObjectFactory
1 protected void addSingletonFactory(String beanName, ObjectFactory> singletonFactory) {
2 Assert.notNull(singletonFactory, "Singleton factory must not be null");
3 synchronized (this.singletonObjects) {
4 if (!this.singletonObjects.containsKey(beanName)) {
5 this.singletonFactories.put(beanName, singletonFactory);
6 this.earlySingletonObjects.remove(beanName);
7 this.registeredSingletons.add(beanName);
8 }
9 }
10 }
1 public Object getSingleton(String beanName) {
2 return getSingleton(beanName, true);
3 }
1 protected Object getSingleton(String beanName, boolean allowEarlyReference) {
2 //从缓存中获取该bean的实例,已经填充了属性值的实例
3 Object singletonObject = this.singletonObjects.get(beanName);
4 //创建bean时,IOC会在this.singletonsCurrentlyInCreation中存一个该bean的名称,表示正在创建这个bean
5 if (singletonObject == null && isSingletonCurrentlyInCreation(beanName)) {
6 synchronized (this.singletonObjects) {
7 //也是从缓存中获取实例,但是这个缓存中的实例是没有经过填充的实例
8 singletonObject = this.earlySingletonObjects.get(beanName);
9 if (singletonObject == null && allowEarlyReference) {
10 //获取生成该bean的beanFactory
11 ObjectFactory> singletonFactory = this.singletonFactories.get(beanName);
12 if (singletonFactory != null) {
13 //获取这个bean的实例
14 singletonObject = singletonFactory.getObject();
15 //将这个还未经填充属性的bean存入新生代缓存中(自己取的名字,类似于JVM)
16 this.earlySingletonObjects.put(beanName, singletonObject);
17 //将这个生产bean的工厂移除
18 this.singletonFactories.remove(beanName);
19 }
20 }
21 }
22 }
23 return (singletonObject != NULL_OBJECT ? singletonObject : null);
24 }