spring源码解析bean初始化与依赖注入四

前言

本文转自“天河聊技术”微信公众号

本次继续介绍spring源码解析bean初始化、依赖注入的部分

 

正文

上次介绍到这个方法

org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#doCreateBean这一行

//     今早的缓存单例对象以便循环引用
      if (earlySingletonExposure) {
         Object earlySingletonReference = getSingleton(beanName, false);
         if (earlySingletonReference != null) {
            if (exposedObject == bean) {
               exposedObject = earlySingletonReference;
            }
//          初始化的bean没被包装又有依赖
            else if (!this.allowRawInjectionDespiteWrapping && hasDependentBean(beanName)) {
//             获取依赖的bean
               String[] dependentBeans = getDependentBeans(beanName);
               Set<String> actualDependentBeans = new LinkedHashSet<>(dependentBeans.length);
               for (String dependentBean : dependentBeans) {
                  if (!removeSingletonIfCreatedForTypeCheckOnly(dependentBean)) {
                     actualDependentBeans.add(dependentBean);
                  }
               }
               if (!actualDependentBeans.isEmpty()) {
                  throw new BeanCurrentlyInCreationException(beanName,
                        "Bean with name '" + beanName + "' has been injected into other beans [" +
                        StringUtils.collectionToCommaDelimitedString(actualDependentBeans) +
                        "] in its raw version as part of a circular reference, but has eventually been " +
                        "wrapped. This means that said other beans do not use the final version of the " +
                        "bean. This is often the result of over-eager type matching - consider using " +
                        "'getBeanNamesOfType' with the 'allowEagerInit' flag turned off, for example.");
               }
            }
         }
      }

这一行

// Register bean as disposable.注册的bean作为可销毁的
try {
   registerDisposableBeanIfNecessary(beanName, bean, mbd);
}

进入org.springframework.beans.factory.support.AbstractBeanFactory#registerDisposableBeanIfNecessary注册可销毁的bean

*/
   protected void registerDisposableBeanIfNecessary(String beanName, Object bean, RootBeanDefinition mbd) {
      AccessControlContext acc = (System.getSecurityManager() != null ? getAccessControlContext() : null);
//    不是原型模式,可以销毁
      if (!mbd.isPrototype() && requiresDestruction(bean, mbd)) {
//       如果是单例
         if (mbd.isSingleton()) {
            // Register a DisposableBean implementation that performs all destruction
            // work for the given bean: DestructionAwareBeanPostProcessors,
            // DisposableBean interface, custom destroy method.
//          注册销毁的bean,这一部分在bean定义解析的部分介绍过,这里不作介绍了
            registerDisposableBean(beanName,
                  new DisposableBeanAdapter(bean, beanName, mbd, getBeanPostProcessors(), acc));
         }
         else {
            // A bean with a custom scope...
            Scope scope = this.scopes.get(mbd.getScope());
            if (scope == null) {
               throw new IllegalStateException("No Scope registered for scope name '" + mbd.getScope() + "'");
            }
//          销毁后的回调方法
            scope.registerDestructionCallback(beanName,
                  new DisposableBeanAdapter(bean, beanName, mbd, getBeanPostProcessors(), acc));
         }
      }
   }

返回org.springframework.beans.factory.support.AbstractBeanFactory#doGetBean这一行

try {
//                   bean初始化
                     return createBean(beanName, mbd, args);
                  }

这里介绍完了,往下

//                    发生异常销毁单例的bean
                     destroySingleton(beanName);

进入

org.springframework.beans.factory.support.DefaultSingletonBeanRegistry#destroySingleton

public void destroySingleton(String beanName) {
      // Remove a registered singleton of the given name, if any.删除单例的bean,从本地缓存中删除
      removeSingleton(beanName);

      // Destroy the corresponding DisposableBean instance.
      DisposableBean disposableBean;
      synchronized (this.disposableBeans) {
//       从本地缓存中删除
         disposableBean = (DisposableBean) this.disposableBeans.remove(beanName);
      }
//    bean销毁的逻辑
      destroyBean(beanName, disposableBean);
   }

这一行

从factoryBean中创建的bean对象
               bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);

这一行

else if (mbd.isPrototype()) {
//             bean定义为原型模式

这一行

      原型的bean创建之前维护内存中的缓存map映射信息
                  beforePrototypeCreation(beanName);
//                原型的bean创建
                  prototypeInstance = createBean(beanName, mbd, args);

进入

org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#createBean(java.lang.String, org.springframework.beans.factory.support.RootBeanDefinition, java.lang.Object[])这一行

//        bean初始化之前执行beanProccessors
         Object bean = resolveBeforeInstantiation(beanName, mbdToUse);

进入

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

@Nullable
   protected Object resolveBeforeInstantiation(String beanName, RootBeanDefinition mbd) {
      Object bean = null;
      if (!Boolean.FALSE.equals(mbd.beforeInstantiationResolved)) {
         // Make sure bean class is actually resolved at this point.
         if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
            Class<?> targetType = determineTargetType(beanName, mbd);
            if (targetType != null) {
//             调用bean初始化前处理器
               bean = applyBeanPostProcessorsBeforeInstantiation(targetType, beanName);
               if (bean != null) {
//                bean初始化以后调用处理器
                  bean = applyBeanPostProcessorsAfterInitialization(bean, beanName);
               }
            }
         }
         mbd.beforeInstantiationResolved = (bean != null);
      }
      return bean;
   }

返回

org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#createBean(java.lang.String, org.springframework.beans.factory.support.RootBeanDefinition, java.lang.Object[])

这一行

//        bean创建
         Object beanInstance = doCreateBean(beanName, mbdToUse, args);

返回

org.springframework.beans.factory.support.AbstractBeanFactory#doGetBean

这一行

如果类型不一致进行类型转换
            T convertedBean = getTypeConverter().convertIfNecessary(bean, requiredType);

返回

org.springframework.beans.factory.support.DefaultListableBeanFactory#preInstantiateSingletons

这一行

for (String beanName : beanNames) {
         Object singletonInstance = getSingleton(beanName);
         if (singletonInstance instanceof SmartInitializingSingleton) {
            final SmartInitializingSingleton smartSingleton = (SmartInitializingSingleton) singletonInstance;
            if (System.getSecurityManager() != null) {
               AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
//                单例bean创建完成后回调
                  smartSingleton.afterSingletonsInstantiated();
                  return null;
               }, getAccessControlContext());
            }
            else {
               smartSingleton.afterSingletonsInstantiated();
            }
         }
      }

bean初始化以后触发回调

这一行

单例bean创建完成后回调
                  smartSingleton.afterSingletonsInstantiated();

返回

org.springframework.context.support.AbstractApplicationContext#refresh

这一行 bean初始化、依赖注入

finishBeanFactoryInitialization(beanFactory);

 

最后

 

本次介绍到这里,以上内容仅供参考。

转载于:https://my.oschina.net/u/3775437/blog/1813308

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值