前言
本文转自“天河聊技术”微信公众号
本次继续介绍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);
最后
本次介绍到这里,以上内容仅供参考。