SpringIOC refresh()初始化代码实例

finishBeanFactoryInitialization(beanFactory):初始化不需要延迟实例化的单例bean

/* org/springframework/context/support/AbstractApplicationContext.java:870 */

protected void finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory) {//初始化容器的conversionService

if (beanFactory.containsBean(CONVERSION_SERVICE_BEAN_NAME) &&

beanFactory.isTypeMatch(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class)) {

beanFactory.setConversionService(

beanFactory.getBean(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class));

}

//如果没有任何一个类似PropertyPlaceholderConfigurer bean处理器

//默认一个嵌入式值解析器,主要是为了解析属性值例如数据库连接中${password}等属性解析

if (!beanFactory.hasEmbeddedValueResolver()) {

beanFactory.addEmbeddedValueResolver(strVal -> getEnvironment().resolvePlaceholders(strVal));

}

// 先实例化LoadTimeWeaverAware相关的beans,以便尽早转换,AOP相关

String[] weaverAwareNames = beanFactory.getBeanNamesForType(LoadTimeWeaverAware.class, false, false);

for (String weaverAwareName : weaverAwareNames) {

getBean(weaverAwareName);

}

//删除临时类加载器,停止临时类加载器进行类型匹配

beanFactory.setTempClassLoader(null);

//拷贝beandefinitionNames到frozenBeanDefinitionNames

beanFactory.freezeConfiguration();

// 实例化所有不需要延迟初始化的单例bean

beanFactory.preInstantiateSingletons();

}

beanFactory.preInstantiateSingletons():实例化所有不需要延迟初始化的单例bean

/* org/springframework/beans/factory/support/DefaultListableBeanFactory.java:885 */

public void preInstantiateSingletons() throws BeansException {

if (logger.isTraceEnabled()) {

logger.trace("Pre-instantiating singletons in " + this);

}

// Iterate over a copy to allow for init methods which in turn register new bean definitions.

// While this may not be part of the regular factory bootstrap, it does otherwise work fine.

//拷贝beanDefinitionNames副本,考虑到遍历中其他线程可能修改beandefinitionNames

// ArrayList类型遍历时规避fast-fail,实现fast-safe

List<String> beanNames = new ArrayList<>(this.beanDefinitionNames);

// Trigger initialization of all non-lazy singleton beans...

for (String beanName : beanNames) {

//当bean存在parentBean时的继承关系

//① bean不存在parentBean时,创建一个new RootBeanDefinition(beandefinition)返回。

//② bean存在parentBean时,支持继承关系

// 需要先创建parentBean的new RootBeanDefinition(parentBeanDefinition)

// 然后用beandefinition覆盖parentBean的RootBeanDefinition的相关属性并返回。superBean.overrideFrom(subBean);

RootBeanDefinition bd = getMergedLocalBeanDefinition(beanName);

//用mergedLocalBeanDefinition判断是否需要初始化

//筛选不是抽象类且不是延迟实例化的单例进行初始化

if (!bd.isAbstract() && bd.isSingleton() && !bd.isLazyInit()) {

if (isFactoryBean(beanName)) {

//工厂Bean beanName=&beanName

Object bean = getBean(FACTORY_BEAN_PREFIX + beanName);

if (bean instanceof FactoryBean) {

final FactoryBean<?> factory = (FactoryBean<?>) bean;

boolean isEagerInit;

if (System.getSecurityManager() != null && factory instanceof SmartFactoryBean) {

isEagerInit = AccessController.doPrivileged((PrivilegedAction<Boolean>)

((SmartFactoryBean<?>) factory)::isEagerInit,

getAccessControlContext());

}

else {

isEagerInit = (factory instanceof SmartFactoryBean &&

((SmartFactoryBean<?>) factory).isEagerInit());

}

if (isEagerInit) {

getBean(beanName);

}

}

}

else {

//不是工厂bean 直接初始化

getBean(beanName);

}

}

}

//SmartInitializingSingleton类型的单例初始化后的回调

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>) () -> {

smartSingleton.afterSingletonsInstantiated();

return null;

}, getAccessControlContext());

}

else {

smartSingleton.afterSingletonsInstantiated();

}

}

}

}

getBean(beanName):Bean初始化

/* org/springframework/beans/factory/support/AbstractBeanFactory.java:414 */

protected <T> T doGetBean(final String name, @Nullable final Class<T> requiredType,

@Nullable final Object[] args, boolean typeCheckOnly) throws BeansException {

//如果是aliaName,解析成beanName

final String beanName = transformedBeanName(name);

Object bean;

// Eagerly check singleton cache for manually registered singletons.

//检查单例缓存中是否存在bean的实例化对象、初始化对象 (涉及循环依赖解决,需要先分清出Bean的两个阶段实例化、初始化)

Object sharedInstance = getSingleton(beanName);

if (sharedInstance != null && args == null) {

if (logger.isTraceEnabled()) {

if (isSingletonCurrentlyInCreation(beanName)) {

logger.trace("Returning eagerly cached instance of singleton bean '" + beanName +

"' that is not fully initialized yet - a consequence of a circular reference");

}

else {

logger.trace("Returning cached instance of singleton bean '" + beanName + "'");

}

}

bean = getObjectForBeanInstance(sharedInstance, name, beanName, null);

}

else {

if (isPrototypeCurrentlyInCreation(beanName)) {

//多例bean正在初始化时抛出异常

//由于多例bean,每调用一次getBean就会创建一个实例,

//所以通过ThreadLocal打标,来避免单个线程的重复创建

throw new BeanCurrentlyInCreationException(beanName);

}

BeanFactory parentBeanFactory = getParentBeanFactory();

//父容器不为空,用父容器初始化

if (parentBeanFactory != null && !containsBeanDefinition(beanName)) {

// Not found -> check parent.

String nameToLookup = originalBeanName(name);

if (parentBeanFactory instanceof AbstractBeanFactory) {

return ((AbstractBeanFactory) parentBeanFactory).doGetBean(

nameToLookup, requiredType, args, typeCheckOnly);

}

else if (args != null) {

// Delegation to parent with explicit args.

return (T) parentBeanFactory.getBean(nameToLookup, args);

}

else if (requiredType != null) {

// No args -> delegate to standard getBean method.

return parentBeanFactory.getBean(nameToLookup, requiredType);

}

else {

return (T) parentBeanFactory.getBean(nameToLookup);

}

}

if (!typeCheckOnly) {

//alreadyCreated容器记录已经被实例化的beanName,

//这里将beanName添加到alreadyCreated

markBeanAsCreated(beanName);

}

try {

//重新获取mergedLocalBeanDefinition(bean与parentBean合并)

final RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);

//检查mbd不是抽象类

checkMergedBeanDefinition(mbd, beanName, args);

//创建bean单例之前,需要保证先bean所依赖的Bean单例已创建,

//这里的依赖对应@dependsOn声明的依赖,这个注解不常用,这里也会出现一种循环依赖场景,与我们平常讨论的引用循环依赖不同

//@dependsOn(value = "b") class A;@dependsOn(value = "a") class B

//如果出现这种循环依赖 会直接抛出异常 启动失败

String[] dependsOn = mbd.getDependsOn();

if (dependsOn != null) {

for (String dep : dependsOn) {

if (isDependent(beanName, dep)) {

throw new BeanCreationException(mbd.getResourceDescription(), beanName,

"Circular depends-on relationship between '" + beanName + "' and '" + dep + "'");

}

//保存依赖关系到dependentBeanMap容器中

registerDependentBean(dep, beanName);

try {

//实例化依赖的bean 这里就是常见循环依赖地点 A依赖B B依赖A

getBean(dep);

}

catch (NoSuchBeanDefinitionException ex) {

throw new BeanCreationException(mbd.getResourceDescription(), beanName,

"'" + beanName + "' depends on missing bean '" + dep + "'", ex);

}

}

}

// Create bean instance.

if (mbd.isSingleton()) {

//单例Bean创建 先取缓存,没有才createBean

sharedInstance = getSingleton(beanName, () -> {

try {

//创建Bean实例

return createBean(beanName, mbd, args);

}

catch (BeansException ex) {

destroySingleton(beanName);

throw ex;

}

});

bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);

}

else if (mbd.isPrototype()) {

//多例Bean创建 直接createbean

Object prototypeInstance = null;

try {

//正在创建bean打标prototypesCurrentlyInCreation

//与上面isPrototypeCurrentlyInCreation()联合

beforePrototypeCreation(beanName);

prototypeInstance = createBean(beanName, mbd, args);

}

finally {

//正在创建bean打标prototypesCurrentlyInCreation删除标记

afterPrototypeCreation(beanName);

}

bean = getObjectForBeanInstance(prototypeInstance, name, beanName, mbd);

}

else {

            //自定义scope初始化、scope.get()

String scopeName = mbd.getScope();

final Scope scope = this.scopes.get(scopeName);

if (scope == null) {

throw new IllegalStateException("No Scope registered for scope name '" + scopeName + "'");

}

try {

Object scopedInstance = scope.get(beanName, () -> {

beforePrototypeCreation(beanName);

try {

return createBean(beanName, mbd, args);

}

finally {

afterPrototypeCreation(beanName);

}

});

bean = getObjectForBeanInstance(scopedInstance, name, beanName, mbd);

}

catch (IllegalStateException ex) {

throw new BeanCreationException(beanName,

"Scope '" + scopeName + "' is not active for the current thread; consider " +

"defining a scoped proxy for this bean if you intend to refer to it from a singleton",

ex);

}

}

}

catch (BeansException ex) {

cleanupAfterBeanCreationFailure(beanName);

throw ex;

}

}

//getBean(beanName,requiredType)时检查创建的实例是否需要的类型,容器初始化时不会走进里面

if (requiredType != null && !requiredType.isInstance(bean)) {

try {

T convertedBean = getTypeConverter().convertIfNecessary(bean, requiredType);

if (convertedBean == null) {

throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass());

}

return convertedBean;

}

catch (TypeMismatchException ex) {

if (logger.isTraceEnabled()) {

logger.trace("Failed to convert bean '" + name + "' to required type '" +

ClassUtils.getQualifiedName(requiredType) + "'", ex);

}

throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass());

}

}

return (T) bean;

}

sharedInstance = getSingleton(beanName, () -> {try {return createBean(beanName, mbd, args);}:单例初始化,这个方法比较简单,主要关注下和循坏依赖相关的逻辑

/* org/springframework/beans/factory/support/DefaultSingletonBeanRegistry.java:201 */

public Object getSingleton(String beanName, ObjectFactory<?> singletonFactory) {

Assert.notNull(beanName, "Bean name must not be null");

synchronized (this.singletonObjects) {

Object singletonObject = this.singletonObjects.get(beanName);

if (singletonObject == null) {

if (this.singletonsCurrentlyInDestruction) {

throw new BeanCreationNotAllowedException(beanName,

"Singleton bean creation not allowed while singletons of this factory are in destruction " +

"(Do not request a bean from a BeanFactory in a destroy method implementation!)");

}

if (logger.isDebugEnabled()) {

logger.debug("Creating shared instance of singleton bean '" + beanName + "'");

}

//循环依赖相关:初始化前先singletonsCurrentlyInCreation.add(beanName)

beforeSingletonCreation(beanName);

boolean newSingleton = false;

boolean recordSuppressedExceptions = (this.suppressedExceptions == null);

if (recordSuppressedExceptions) {

this.suppressedExceptions = new LinkedHashSet<>();

}

try {

//lamda表达式:其实是调用createBean(beanName, mbd, args):Bean初始化

singletonObject = singletonFactory.getObject();

newSingleton = true;

}

catch (IllegalStateException ex) {

// Has the singleton object implicitly appeared in the meantime ->

// if yes, proceed with it since the exception indicates that state.

singletonObject = this.singletonObjects.get(beanName);

if (singletonObject == null) {

throw ex;

}

}

catch (BeanCreationException ex) {

if (recordSuppressedExceptions) {

for (Exception suppressedException : this.suppressedExceptions) {

ex.addRelatedCause(suppressedException);

}

}

throw ex;

}

finally {

if (recordSuppressedExceptions) {

this.suppressedExceptions = null;

}

//循环依赖相关:初始化后singletonsCurrentlyInCreation.remove(beanName)

afterSingletonCreation(beanName);

}

if (newSingleton) {

//初始化完后

//this.singletonObjects.put(beanName, singletonObject);放入到单例容器中

//this.singletonFactories.remove(beanName);清空循环依赖相关的两个打标

//this.earlySingletonObjects.remove(beanName);

//this.registeredSingletons.add(beanName);放入单例beanName容器中

addSingleton(beanName, singletonObject);

}

}

return singletonObject;

}

}

createBean(beanName, mbd, args):初始化实例,这个表方法注意一下,初始化实例前,留机会给BeanPostProcessor初始化代理类直接返回代理类初始化实例

/* org/springframework/beans/factory/support/AbstractAutowireCapableBeanFactory.java:467 */

protected Object createBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)

throws BeanCreationException {

if (logger.isTraceEnabled()) {

logger.trace("Creating instance of bean '" + beanName + "'");

}

RootBeanDefinition mbdToUse = mbd;

Class<?> resolvedClass = resolveBeanClass(mbd, beanName);

if (resolvedClass != null && !mbd.hasBeanClass() && mbd.getBeanClassName() != null) {

//确保beanclass确实被解析了,若合并出错,重新定义bean定义

mbdToUse = new RootBeanDefinition(mbd);

mbdToUse.setBeanClass(resolvedClass);

}

// Prepare method overrides.

try {

//校验需要重写方法是否全部重写,并且会给重写方法是否重载打标

mbdToUse.prepareMethodOverrides();

}

catch (BeanDefinitionValidationException ex) {

throw new BeanDefinitionStoreException(mbdToUse.getResourceDescription(),

beanName, "Validation of method overrides failed", ex);

}

try {

//resolveBeforeInstantiation方法是调用BeanPostProcessor处理器

//后续研究一下BeanPostProcessor

//这里是给AOP相关BeanPostProcessor处理器生成代理类实例的机会,直接生成初始化代理类实例返回

//会面研究AOP时发现,proxy object不是在这里初始化,这里只是提供一个机会

//proxy object具体是在的下面doCreateBean时里先创建target object

//然后通过后置处理器的后置方法初始化的

Object bean = resolveBeforeInstantiation(beanName, mbdToUse);

if (bean != null) {

return bean;

}

}

catch (Throwable ex) {

throw new BeanCreationException(mbdToUse.getResourceDescription(), beanName,

"BeanPostProcessor before instantiation of bean failed", ex);

}

try {

//初始化实例

Object beanInstance = doCreateBean(beanName, mbdToUse, args);

if (logger.isTraceEnabled()) {

logger.trace("Finished creating instance of bean '" + beanName + "'");

}

return beanInstance;

}

catch (BeanCreationException | ImplicitlyAppearedSingletonException ex) {

// A previously detected exception with proper bean creation context already,

// or illegal singleton state to be communicated up to DefaultSingletonBeanRegistry.

throw ex;

}

catch (Throwable ex) {

throw new BeanCreationException(

mbdToUse.getResourceDescription(), beanName, "Unexpected exception during bean creation", ex);

}

}

doCreateBean(beanName,mbdToUse,args):beanClass实例化(即earlysingleton,注意不是初始化)然后DI完成初始化

/* org/springframework/beans/factory/support/AbstractAutowireCapableBeanFactory.java:549 */

protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final @Nullable Object[] args)

throws BeanCreationException {

// Instantiate the bean.

BeanWrapper instanceWrapper = null;

if (mbd.isSingleton()) {

instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);

}

if (instanceWrapper == null) {

//反射调用beanClass的构造方法创建实例并包装成beanwrapper--

instanceWrapper = createBeanInstance(beanName, mbd, args);

}

final Object bean = instanceWrapper.getWrappedInstance();

Class<?> beanType = instanceWrapper.getWrappedClass();

if (beanType != NullBean.class) {

mbd.resolvedTargetType = beanType;

}

// Allow post-processors to modify the merged bean definition.

//允许MergedBeanDefinitionPostProcessors后置管理器修改rootBeandefinition

synchronized (mbd.postProcessingLock) {

if (!mbd.postProcessed) {

try {

applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);

}

catch (Throwable ex) {

throw new BeanCreationException(mbd.getResourceDescription(), beanName,

"Post-processing of merged bean definition failed", ex);

}

mbd.postProcessed = true;

}

}

// Eagerly cache singletons to be able to resolve circular references

// even when triggered by lifecycle interfaces like BeanFactoryAware.

boolean earlySingletonExposure = (mbd.isSingleton() && this.allowCircularReferences &&

isSingletonCurrentlyInCreation(beanName));

if (earlySingletonExposure) {

if (logger.isTraceEnabled()) {

logger.trace("Eagerly caching bean '" + beanName +

"' to allow for resolving potential circular references");

}

//循环依赖相关逻辑:

//this.singletonFactories.put(beanName, singletonFactory);

//将实例化bean、beanName组装成singletonFactory装入singletonFactories容器

//this.earlySingletonObjects.remove(beanName);

//删除earlySingletonObjects中beanName

addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean));

}

// Initialize the bean instance.

//创建实例

Object exposedObject = bean;

try {

//实例初始化 就是在这里面实现依赖注入DI的:

//具体是调用AutowiredAnnotationBeanPostProcessor.postProcessProperties

populateBean(beanName, mbd, instanceWrapper);//调用Bean后置管理器前置方法BeanPostProcessor.postProcessBeforeInitialization

//instanceof aware接口,setBeanName setBeanClassLoader setBeanFactory

//调用Bean后置管理器后置方法BeanPostProcessor.postProcessAfterInitialization

exposedObject = initializeBean(beanName, exposedObject, mbd);

}

catch (Throwable ex) {

if (ex instanceof BeanCreationException && beanName.equals(((BeanCreationException) ex).getBeanName())) {

throw (BeanCreationException) ex;

}

else {

throw new BeanCreationException(

mbd.getResourceDescription(), beanName, "Initialization of bean failed", ex);

}

}

//...

return exposedObject;

}

populateBean(beanName, mbd, instanceWrapper):依赖注入DI执行时机

/* org/springframework/beans/factory/support/AbstractAutowireCapableBeanFactory.java:1381 */

protected void populateBean(String beanName, RootBeanDefinition mbd, @Nullable BeanWrapper bw) {

//...

PropertyDescriptor[] filteredPds = null;

if (hasInstAwareBpps) {

if (pvs == null) {

pvs = mbd.getPropertyValues();

}

for (BeanPostProcessor bp : getBeanPostProcessors()) {

if (bp instanceof InstantiationAwareBeanPostProcessor) {

InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;

//这里调用AutowiredAnnotationBeanPostProcessor.postProcessProperties()

//完成注解自动注入(DI)

PropertyValues pvsToUse = ibp.postProcessProperties(pvs, bw.getWrappedInstance(), beanName);

if (pvsToUse == null) {

if (filteredPds == null) {

filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);

}

pvsToUse = ibp.postProcessPropertyValues(pvs, filteredPds, bw.getWrappedInstance(), beanName);

if (pvsToUse == null) {

return;

}

}

pvs = pvsToUse;

}

}

}

if (needsDepCheck) {

if (filteredPds == null) {

filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);

}

checkDependencies(beanName, mbd, filteredPds, pvs);

}

if (pvs != null) {

applyPropertyValues(beanName, mbd, bw, pvs);

}

}

DI结束,bean初始化基本结束了。然后就是bean初始化的BeanPostProcessor执行前置后置方法

BeanPostProcessor前置后置方法:一些很重要架构都需要依靠实现,例如AOP动态代理产生代理对象

AnnotationAwareAspectJAutoProxyCreator.postProcessAfterInitialization

/* org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#initializeBean(java.lang.String, java.lang.Object, org.springframework.beans.factory.support.RootBeanDefinition) */

protected Object initializeBean(final String beanName, final Object bean, @Nullable RootBeanDefinition mbd) {

if (System.getSecurityManager() != null) {

AccessController.doPrivileged((PrivilegedAction<Object>) () -> {

invokeAwareMethods(beanName, bean);

return null;

}, getAccessControlContext());

}

else {

invokeAwareMethods(beanName, bean);

}

Object wrappedBean = bean;

if (mbd == null || !mbd.isSynthetic()) {

//调用所有BeanPostProcessor前置方法BeanPostProcessor.postProcessBeforeInitialization

wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);

}

try {

invokeInitMethods(beanName, wrappedBean, mbd);

}

catch (Throwable ex) {

throw new BeanCreationException(

(mbd != null ? mbd.getResourceDescription() : null),

beanName, "Invocation of init method failed", ex);

}

if (mbd == null || !mbd.isSynthetic()) {

//调用所有BeanPostProcessor前置方法BeanPostProcessor.postProcessAfterInitialization

//例如AOP代理对象就是这里初始化的,AnnotationAwareAspectJAutoProxyCreator.postProcessAfterInitialization

wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);

}

return wrappedBean;

}

以上是 SpringIOC refresh()初始化代码实例 的全部内容, 来源链接: utcz.com/z/353742.html

回到顶部