热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

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

2019独角兽企业重金招聘Python工程师标准前言本文转自“天河聊技术”微信公众号本次继续介绍spring源码解析bean初始化、依赖注入的部分正文上次介绍到这个方法org



2019独角兽企业重金招聘Python工程师标准>>> hot3.png



前言


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


本次继续介绍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 actualDependentBeans &#61; new LinkedHashSet<>(dependentBeans.length);
              for (String dependentBean : dependentBeans) {
if (!removeSingletonIfCreatedForTypeCheckOnly(dependentBean)) {
actualDependentBeans.add(dependentBean);
                 }
}
if (!actualDependentBeans.isEmpty()) {
throw new BeanCurrentlyInCreationException(beanName,
                       "Bean with name &#39;" &#43; beanName &#43; "&#39; has been injected into other beans [" &#43;
StringUtils.collectionToCommaDelimitedString(actualDependentBeans) &#43;
"] in its raw version as part of a circular reference, but has eventually been " &#43;
"wrapped. This means that said other beans do not use the final version of the " &#43;
"bean. This is often the result of over-eager type matching - consider using " &#43;
"&#39;getBeanNamesOfType&#39; with the &#39;allowEagerInit&#39; 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 &#61; (System.getSecurityManager() !&#61; null ? getAccessControlContext() : null);
//    不是原型模式&#xff0c;可以销毁
     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&#xff0c;这一部分在bean定义解析的部分介绍过&#xff0c;这里不作介绍了
           registerDisposableBean(beanName,
                 new DisposableBeanAdapter(bean, beanName, mbd, getBeanPostProcessors(), acc));
        }
else {
// A bean with a custom scope...
           Scope scope &#61; this.scopes.get(mbd.getScope());
           if (scope &#61;&#61; null) {
throw new IllegalStateException("No Scope registered for scope name &#39;" &#43; mbd.getScope() &#43; "&#39;");
           }
//          销毁后的回调方法
           scope.registerDestructionCallback(beanName,
                 new DisposableBeanAdapter(bean, beanName, mbd, getBeanPostProcessors(), acc));
        }
}
}

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


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

这里介绍完了&#xff0c;往下


//                    发生异常销毁单例的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&#xff0c;从本地缓存中删除
     removeSingleton(beanName);
     // Destroy the corresponding DisposableBean instance.
     DisposableBean disposableBean;
     synchronized (this.disposableBeans) {
//       从本地缓存中删除
        disposableBean &#61; (DisposableBean) this.disposableBeans.remove(beanName);
     }
//    bean销毁的逻辑
     destroyBean(beanName, disposableBean);
  }

这一行


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

这一行


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

这一行


      原型的bean创建之前维护内存中的缓存map映射信息
                 beforePrototypeCreation(beanName);
//                原型的bean创建
                 prototypeInstance &#61; 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 &#61; resolveBeforeInstantiation(beanName, mbdToUse);

进入


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


&#64;Nullable
  protected Object resolveBeforeInstantiation(String beanName, RootBeanDefinition mbd) {
Object bean &#61; null;
     if (!Boolean.FALSE.equals(mbd.beforeInstantiationResolved)) {
// Make sure bean class is actually resolved at this point.
        if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
Class targetType &#61; determineTargetType(beanName, mbd);
           if (targetType !&#61; null) {
//             调用bean初始化前处理器
              bean &#61; applyBeanPostProcessorsBeforeInstantiation(targetType, beanName);
              if (bean !&#61; null) {
//                bean初始化以后调用处理器
                 bean &#61; applyBeanPostProcessorsAfterInitialization(bean, beanName);
              }
}
}
mbd.beforeInstantiationResolved &#61; (bean !&#61; 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 &#61; doCreateBean(beanName, mbdToUse, args);

返回


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


这一行


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

返回


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


这一行


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

bean初始化以后触发回调


这一行


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

返回


org.springframework.context.support.AbstractApplicationContext#refresh


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


finishBeanFactoryInitialization(beanFactory);

 


最后


 


本次介绍到这里&#xff0c;以上内容仅供参考。







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



推荐阅读
author-avatar
少钧13
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有