实验环境:spring-framework-5.0.2、jdk8、gradle4.3.1

有两种情况会触发bean的实例化:一种是懒加载的bean,会在容器初始化时,也就是AbstractApplicationContext#refresh方法的第11步触发;另外懒加载的bean会在容器初始化完成,具体调用getBean方法时,发现缓存里没有,触发实例化。两者最终都会走到getBean方法里。

为了更系统的描述bean实例化过程,我们从AbstractApplicationContext#refresh方法的第11步finishBeanFactoryInitialization方法为入口开始看

AbstractApplicationContext#finishBeanFactoryInitialization方法
    /**
* 完成此上下文的bean工厂的初始化,初始化所有剩余的单例bean。
*/
protected void finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory) {
// 1.初始化此上下文的转换服务
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));
} // 2.如果beanFactory之前没有注册嵌入值解析器,则注册默认的嵌入值解析器:主要用于注解属性值的解析。
if (!beanFactory.hasEmbeddedValueResolver()) {
beanFactory.addEmbeddedValueResolver(strVal -> getEnvironment().resolvePlaceholders(strVal));
} // 3.初始化LoadTimeWeaverAware Bean实例对象
String[] weaverAwareNames = beanFactory.getBeanNamesForType(LoadTimeWeaverAware.class,
false, false);
for (String weaverAwareName : weaverAwareNames) {
getBean(weaverAwareName);
} beanFactory.setTempClassLoader(null); // 4.冻结所有bean定义,注册的bean定义不会被修改或进一步后处理,因为马上要创建 Bean 实例对象了
beanFactory.freezeConfiguration(); // 5.实例化所有剩余(非懒加载)单例对象(实例化入口)
beanFactory.preInstantiateSingletons();
}

beanFactory.preInstantiateSingletons()是开始实例化的入口,里面会调用getBean方法,也就是说会触发一下实例化存入缓存中

DefaultListableBeanFactory#preInstantiateSingletons方法
/**
* 实例化所有剩余(非懒加载)单例对象
*/
@Override
public void preInstantiateSingletons() throws BeansException {
if (this.logger.isDebugEnabled()) {
this.logger.debug("Pre-instantiating singletons in " + this);
} // 1.创建beanDefinitionNames的副本beanNames用于后续的遍历,以允许init等方法注册新的bean定义
List<String> beanNames = new ArrayList<>(this.beanDefinitionNames); // 2.遍历beanNames,触发所有非懒加载单例bean的初始化
for (String beanName : beanNames) { // 3.获取beanName对应的MergedBeanDefinition
RootBeanDefinition bd = getMergedLocalBeanDefinition(beanName); // 4.bd对应的Bean实例:不是抽象类 && 是单例 && 不是懒加载
if (!bd.isAbstract() && bd.isSingleton() && !bd.isLazyInit()) { // 如果当前bean是FactoryBean,即bean继承了FactoryBean接口
if (isFactoryBean(beanName)) { // 5.1 通过beanName获取FactoryBean实例
// 通过getBean(&beanName)拿到的是FactoryBean本身;通过getBean(beanName)拿到的是FactoryBean创建的Bean实例
final FactoryBean<?> factory = (FactoryBean<?>) getBean(FACTORY_BEAN_PREFIX + beanName); // 5.2 判断这个FactoryBean是否希望急切的初始化
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) {
// 5.3 如果希望急切的初始化,则通过beanName获取bean实例
getBean(beanName);
}
}
else {
// 6.如果beanName对应的bean不是FactoryBean,只是普通Bean,通过beanName获取bean实例
getBean(beanName);
}
}
} // 7.遍历beanNames,触发所有SmartInitializingSingleton的后初始化回调
for (String beanName : beanNames) { // 7.1 拿到beanName对应的bean实例
Object singletonInstance = getSingleton(beanName); // 7.2 判断singletonInstance是否实现了SmartInitializingSingleton接口
if (singletonInstance instanceof SmartInitializingSingleton) {
final SmartInitializingSingleton smartSingleton = (SmartInitializingSingleton) singletonInstance; // 7.3 触发SmartInitializingSingleton实现类的afterSingletonsInstantiated方法
if (System.getSecurityManager() != null) {
AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
smartSingleton.afterSingletonsInstantiated();
return null;
}, getAccessControlContext());
}
else {
smartSingleton.afterSingletonsInstantiated();
}
}
}
}

我们再具体看一下getBean方法,逻辑在父类AbstractBeanFactory中,具体流程如图所示,这个图就是根据代码执行流程画的

AbstractBeanFactory#getBean方法
@Override
public Object getBean(String name) throws BeansException {
Object o = doGetBean(name, null, null, false);
return o;
} /**
* 真正实现向IOC容器获取bean的功能,也是触发依赖注入的地方
*/
@SuppressWarnings("unchecked")
protected <T> T doGetBean(final String name, @Nullable final Class<T> requiredType,
@Nullable final Object[] args, boolean typeCheckOnly) throws BeansException { // 1.将name解析成真正的beanName(bean配置的id),主要是去掉 FactoryBean 里的 “&” 前缀,和别名转标准bean名称
final String beanName = transformedBeanName(name);
Object bean; // 2.先从缓存中获取是否已经创建了单例对象【getSingleton方法里设置了三级缓存,解决了循环依赖的问题】
// 缓存里面没有的话,才会往下走进行bean的创建
Object sharedInstance = getSingleton(beanName);
if (sharedInstance != null && args == null) {
// 3.如果beanName的实例存在于缓存中
if (logger.isDebugEnabled()) {
if (isSingletonCurrentlyInCreation(beanName)) {
logger.debug("Returning eagerly cached instance of singleton bean '" + beanName +
"' that is not fully initialized yet - a consequence of a circular reference");
}
else {
logger.debug("Returning cached instance of singleton bean '" + beanName + "'");
}
} // 3.1 返回beanName对应的实例对象(主要用于FactoryBean的特殊处理,普通Bean会直接返回sharedInstance本身)
// 注意:BeanFactory是管理bean的工厂,FactoryBean是创建对象的工厂bean
bean = getObjectForBeanInstance(sharedInstance, name, beanName, null);
} else {
// 来到这里就说明要获取的bean还没有实例化过 // 4.原型模式的循环依赖校验:如果正在创建Bean实例中,而此时我们又要再一次创建beanName的实例,则代表出现了循环依赖,需要抛出异常。
// 例子:如果存在A中有B的属性,B中有A的属性,那么当依赖注入的时候,就会产生当A还未创建完的时候因为对于B的创建再次返回创建A,造成循环依赖
if (isPrototypeCurrentlyInCreation(beanName)) {
throw new BeanCurrentlyInCreationException(beanName);
} // 5.获取父BeanFactory
BeanFactory parentBeanFactory = getParentBeanFactory(); // 5.1 如果parentBeanFactory存在,并且beanName在当前BeanFactory不存在Bean定义,则尝试从parentBeanFactory中获取bean实例
if (parentBeanFactory != null && !containsBeanDefinition(beanName)) { // 5.2 将别名解析成真正的beanName
String nameToLookup = originalBeanName(name);
if (parentBeanFactory instanceof AbstractBeanFactory) {
return ((AbstractBeanFactory) parentBeanFactory).doGetBean(
nameToLookup, requiredType, args, typeCheckOnly);
} // 5.3 尝试在parentBeanFactory中获取bean对象实例
else if (args != null) {
// 父容器根据名称和参数查找
return (T) parentBeanFactory.getBean(nameToLookup, args);
}
else {
//父容器根据名称和类型查找
return parentBeanFactory.getBean(nameToLookup, requiredType);
}
} // 走到这一步,说明父容器里找不到bean if (!typeCheckOnly) {
// 6.将当前的beanName存放到AlreadeyCreated这个set集中,标识这个bean被创建了
markBeanAsCreated(beanName);
} try {
// 7.根据beanName获取RootBeanDefinition,主要解决bean继承时子类和父类公共属性问题
final RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
// 7.1 检查MergedBeanDefinition
checkMergedBeanDefinition(mbd, beanName, args); // 8.拿到当前bean依赖的bean名称集合,在实例化自己之前,需要先实例化自己依赖的bean
String[] dependsOn = mbd.getDependsOn();
if (dependsOn != null) {
// 8.1 遍历当前bean依赖的bean名称集合
for (String dep : dependsOn) {
// 8.2 检查dep是否依赖于beanName,即检查是否存在循环依赖
if (isDependent(beanName, dep)) {
// 8.3 如果是循环依赖则抛异常
throw new BeanCreationException(mbd.getResourceDescription(), beanName,
"Circular depends-on relationship between '" + beanName + "' and '" + dep + "'");
}
// 8.4 将dep和beanName的依赖关系注册到缓存中
registerDependentBean(dep, beanName);
// 8.5 递归调用,获取当前bean的依赖bean
getBean(dep);
}
} // 走到这一步,bean的依赖已经处理完了 // 9.创建单例bean实例,只创建一次,存入缓存中
if (mbd.isSingleton()) {
// 9.1 9.1 实例化单例bean(通过ObjectFactory匿名内部类创建bean实例)并存入一级缓存singletonObjects
sharedInstance = getSingleton(beanName, () -> {
try {
// 9.1.1 【重要】真正完成Bean实例的创建
Object o = createBean(beanName, mbd, args); return o;
}
catch (BeansException ex) {
// 清除bean实例
destroySingleton(beanName);
throw ex;
}
});
// 9.1.2 返回beanName对应的实例对象(主要用于FactoryBean的特殊处理,普通Bean会直接返回sharedInstance本身)
bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
} // 9.2 创建原型bean实例,每次都会创建一个新实例
else if (mbd.isPrototype()) {
Object prototypeInstance = null;
try {
// 9.2.1 创建实例前的操作,注册当前对象(将beanName保存到prototypesCurrentlyInCreation缓存中)
// 也就是把beanName存入ThreadLocal当前线程的set中
beforePrototypeCreation(beanName); // 9.2.2 创建Bean实例
prototypeInstance = createBean(beanName, mbd, args);
}
finally {
// 9.2.3 创建实例后的操作(将创建完的beanName从prototypesCurrentlyInCreation缓存中移除)
afterPrototypeCreation(beanName);
}
// 9.2.4 返回beanName对应的实例对象
bean = getObjectForBeanInstance(prototypeInstance, name, beanName, mbd);
} // 9.3 其他作用域范围的bean(比如request、session、application等生命周期)
else {
// 9.3.1 根据scopeName,从缓存拿到scope实例,进行校验作用域是否合法
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 {
// 9.3.2 在当前作用域创建bean实例,也就是说该bean在当前作用域是单例的
Object scopedInstance = scope.get(beanName, () -> {
// 9.3.3 创建实例前的操作(将beanName保存到prototypesCurrentlyInCreation缓存中)
beforePrototypeCreation(beanName);
try {
// 9.3.4 创建bean实例
return createBean(beanName, mbd, args);
}
finally {
// 9.3.5 创建实例后的操作(将创建完的beanName从prototypesCurrentlyInCreation缓存中移除)
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) {
// 如果创建bean实例过程中出现异常,则将beanName从alreadyCreated缓存中移除
cleanupAfterBeanCreationFailure(beanName);
throw ex;
}
} // 10.检查所需类型是否与实际的bean对象的类型匹配
if (requiredType != null && !requiredType.isInstance(bean)) {
try {
// 10.1 类型不对,则尝试转换bean类型
T convertedBean = getTypeConverter().convertIfNecessary(bean, requiredType);
if (convertedBean == null) {
throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass());
}
return convertedBean;
}
catch (TypeMismatchException ex) {
if (logger.isDebugEnabled()) {
logger.debug("Failed to convert bean '" + name + "' to required type '" +
ClassUtils.getQualifiedName(requiredType) + "'", ex);
}
throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass());
}
}
// 11.返回创建出来的bean实例对象
return (T) bean;
}

由上面代码,我们看到会先从缓存里获取,缓存没有会进行bean的创建,然后存入一级缓存。我们先看一下getSingleton方法,会调用工厂方法创建一个bean,然后添加到一级缓存中

DefaultSingletonBeanRegistry#getSingleton方法
/**
* 通过singletonFactory创建bean实例,并存入一级缓存singletonObjects
*/
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 + "'");
} // 校验是否已经在创建中,抛出异常
beforeSingletonCreation(beanName); boolean newSingleton = false;
boolean recordSuppressedExceptions = (this.suppressedExceptions == null);
if (recordSuppressedExceptions) {
this.suppressedExceptions = new LinkedHashSet<>();
} try {
// 【在这里创建实例】singletonFactory创建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;
}
afterSingletonCreation(beanName);
}
if (newSingleton) {
// TODO【重要】把bean实例加入缓存
addSingleton(beanName, singletonObject);
}
}
return singletonObject;
}
} /**
* 向一级缓存添加bean实例
*/
protected void addSingleton(String beanName, Object singletonObject) {
synchronized (this.singletonObjects) {
this.singletonObjects.put(beanName, singletonObject);
this.singletonFactories.remove(beanName);
this.earlySingletonObjects.remove(beanName);
this.registeredSingletons.add(beanName);
}
}

上面getSingleton方法调用createBean方法来创建了一个bean对象,我们再看一下createBean方法

AbstractAutowireCapableBeanFactory#createBean方法
/**
* AbstractAutowireCapableBeanFactory类 创建bean实例
*/
@Override
protected Object createBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)
throws BeanCreationException { if (logger.isDebugEnabled()) {
logger.debug("Creating instance of bean '" + beanName + "'");
}
RootBeanDefinition mbdToUse = mbd; // 判断需要创建的bean是否可实例化,即是否可以通过当前的类加载器加载
Class<?> resolvedClass = resolveBeanClass(mbd, beanName);
if (resolvedClass != null && !mbd.hasBeanClass() && mbd.getBeanClassName() != null) {
mbdToUse = new RootBeanDefinition(mbd);
mbdToUse.setBeanClass(resolvedClass);
} // 校验和准备bean中的方法覆盖
try {
mbdToUse.prepareMethodOverrides();
}
catch (BeanDefinitionValidationException ex) {
throw new BeanDefinitionStoreException(mbdToUse.getResourceDescription(),
beanName, "Validation of method overrides failed", ex);
} try {
// 如果bean配置了初始化前和初始化后的处理器,则尝试返回一个需要创建bean的代理对象
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 {
// TODO【重要】创建bean的入口
Object beanInstance = doCreateBean(beanName, mbdToUse, args);
if (logger.isDebugEnabled()) {
logger.debug("Finished creating instance of bean '" + beanName + "'");
}
return beanInstance;
}
catch (BeanCreationException ex) {
// A previously detected exception with proper bean creation context already...
throw ex;
}
catch (ImplicitlyAppearedSingletonException ex) {
// An IllegalStateException to be communicated up to DefaultSingletonBeanRegistry...
throw ex;
}
catch (Throwable ex) {
throw new BeanCreationException(
mbdToUse.getResourceDescription(), beanName, "Unexpected exception during bean creation", ex);
}
}

我们具体来看一下doCreateBean方法,其执行步骤如下

AbstractAutowireCapableBeanFactory#doCreateBean方法
    /**
* 真正创建bean的方法
*/
protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final @Nullable Object[] args)
throws BeanCreationException { // 封装被创建的bean对象
BeanWrapper instanceWrapper = null;
if (mbd.isSingleton()) {
instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);
}
if (instanceWrapper == null) {
// TODO【重要】 这一步创建了bean实例,只是一个早期的对象,还没有填充属性值
instanceWrapper = createBeanInstance(beanName, mbd, args);
}
final Object bean = instanceWrapper.getWrappedInstance(); // 获取实例化对象的类型
Class<?> beanType = instanceWrapper.getWrappedClass();
if (beanType != NullBean.class) {
mbd.resolvedTargetType = beanType;
} // 调用post-processors后置处理器
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;
}
} // 向容器中缓存单例模式的bean,防止循环引用
boolean earlySingletonExposure = (mbd.isSingleton() && this.allowCircularReferences &&
isSingletonCurrentlyInCreation(beanName));
if (earlySingletonExposure) {
if (logger.isDebugEnabled()) {
logger.debug("Eagerly caching bean '" + beanName +
"' to allow for resolving potential circular references");
}
// TODO【重要】 向三级缓存添加bean实例 匿名内部类,防止循环引用,尽早持有对象的引用
addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean));
} // 初始化bean实例,exposedObject在初始化完成之后返回依赖注入完成之后的bean
Object exposedObject = bean;
try {
// TODO 【重要】 bean属性依赖注入,并且将bean定义中配置的属性值赋值给实例对象
populateBean(beanName, mbd, instanceWrapper); // TODO 【重要】开始初始化bean对象 调用Aware接口方法 -> 调用BeanPostProcessor.before方法 -> 调用init-method方法 -> 调用BeanPostProcessor.after方法
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);
}
} if (earlySingletonExposure) {
// 获取指定名称的已注册的单例bean
Object earlySingletonReference = getSingleton(beanName, false);
if (earlySingletonReference != null) {
// 根据名称获取已注册的bean和正在实例化的bean是同一个
if (exposedObject == bean) {
// 当前实例化的bean初始完成
exposedObject = earlySingletonReference;
}
// 当前bean依赖其他bean,且当发送循环引用时,不允许创建新的实例对象
else if (!this.allowRawInjectionDespiteWrapping && hasDependentBean(beanName)) {
// 获取当前bean所依赖的其他bean
String[] dependentBeans = getDependentBeans(beanName);
Set<String> actualDependentBeans = new LinkedHashSet<>(dependentBeans.length);
for (String dependentBean : dependentBeans) {
// 对依赖bean进行类型检查
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.");
}
}
}
} // 注册完成依赖注入的bean
try {
registerDisposableBeanIfNecessary(beanName, bean, mbd);
}
catch (BeanDefinitionValidationException ex) {
throw new BeanCreationException(
mbd.getResourceDescription(), beanName, "Invalid destruction signature", ex);
} return exposedObject;
}

doCreateBean方法执行结束,就会创建一个完整的bean对象。

想要再深入看的话,我们可以看几个核心方法:createBeanInstance方法(创建bean实例)、addSingletonFactory方法(向三级缓存添加bean实例)、initializeBean方法(初始化bean)

AbstractAutowireCapableBeanFactory#createBeanInstance方法:其实就是调用了反射或cglib来创建一个对象

查看代码
/**
* 创建bean实例对象
*/
protected BeanWrapper createBeanInstance(String beanName, RootBeanDefinition mbd, @Nullable Object[] args) {
// 确认bean可实例化
Class<?> beanClass = resolveBeanClass(mbd, beanName); // 使用工厂方法对bean进行实例化
if (beanClass != null && !Modifier.isPublic(beanClass.getModifiers()) && !mbd.isNonPublicAccessAllowed()) {
throw new BeanCreationException(mbd.getResourceDescription(), beanName,
"Bean class isn't public, and non-public access not allowed: " + beanClass.getName());
} Supplier<?> instanceSupplier = mbd.getInstanceSupplier();
if (instanceSupplier != null) {
return obtainFromSupplier(instanceSupplier, beanName);
} if (mbd.getFactoryMethodName() != null) {
// 调用工厂方法进行实例化
return instantiateUsingFactoryMethod(beanName, mbd, args);
} // 使用容器的自动装配方法进行实例化
boolean resolved = false;
boolean autowireNecessary = false;
if (args == null) {
synchronized (mbd.constructorArgumentLock) {
if (mbd.resolvedConstructorOrFactoryMethod != null) {
resolved = true;
autowireNecessary = mbd.constructorArgumentsResolved;
}
}
}
if (resolved) {
if (autowireNecessary) {
// 配置了自动装配属性,容器的自动装配
return autowireConstructor(beanName, mbd, null, null);
}
else {
// 使用默认无参构造方法实例化
return instantiateBean(beanName, mbd);
}
} // 使用bean的构造方法进行实例化 (开始使用反射来实例化)
Constructor<?>[] ctors = determineConstructorsFromBeanPostProcessors(beanClass, beanName);
if (ctors != null ||
mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_CONSTRUCTOR ||
mbd.hasConstructorArgumentValues() || !ObjectUtils.isEmpty(args)) {
return autowireConstructor(beanName, mbd, ctors, args);
} //【重要】 使用默认的无参构造方法进行实例化
return instantiateBean(beanName, mbd);
} /**
* 使用默认构造方法实例化bean
*/
protected BeanWrapper instantiateBean(final String beanName, final RootBeanDefinition mbd) {
try {
Object beanInstance;
final BeanFactory parent = this;
// 获取系统的安全管理接口,jdk标准的安全管理api
if (System.getSecurityManager() != null) {
// 匿名内部类,根据实例化策略创建实例对象
beanInstance = AccessController.doPrivileged((PrivilegedAction<Object>) () ->
getInstantiationStrategy().instantiate(mbd, beanName, parent),
getAccessControlContext());
}
else {
//【重要】获取实例化策略 执行实例化
beanInstance = getInstantiationStrategy().instantiate(mbd, beanName, parent);
}
// 将实例化对象封装起来
BeanWrapper bw = new BeanWrapperImpl(beanInstance);
initBeanWrapper(bw);
return bw;
}
catch (Throwable ex) {
throw new BeanCreationException(
mbd.getResourceDescription(), beanName, "Instantiation of bean failed", ex);
}
} /**
* 使用初始化策略实例化对象
* 如果Bean的方法被覆盖了,则使用CGLib进行实例化,否则使用JDK的反射机制进行实例化。
*/
@Override
public Object instantiate(RootBeanDefinition bd, @Nullable String beanName, BeanFactory owner) {
// 如果bean定义中没有方法覆盖,就不需要使用cglib父类的方法
if (!bd.hasMethodOverrides()) {
Constructor<?> constructorToUse;
synchronized (bd.constructorArgumentLock) {
// 获取对象的构造方法或工厂方法
constructorToUse = (Constructor<?>) bd.resolvedConstructorOrFactoryMethod;
// 如果没有构造方法或工厂方法
if (constructorToUse == null) {
// 使用jdk的反射机制,判断实例化的bean是否是接口
final Class<?> clazz = bd.getBeanClass();
if (clazz.isInterface()) {
throw new BeanInstantiationException(clazz, "Specified class is an interface");
}
try {
if (System.getSecurityManager() != null) {
// 匿名内部类,使用反射机制获取bean的构造方法
constructorToUse = AccessController.doPrivileged(
(PrivilegedExceptionAction<Constructor<?>>) () -> clazz.getDeclaredConstructor());
}
else {
constructorToUse = clazz.getDeclaredConstructor();
}
bd.resolvedConstructorOrFactoryMethod = constructorToUse;
}
catch (Throwable ex) {
throw new BeanInstantiationException(clazz, "No default constructor found", ex);
}
}
}
//【重要】使用BeanUtils进行实例化,通过反射机制调用构造方法newInstance(arg)来实例化对象
return BeanUtils.instantiateClass(constructorToUse);
}
else {
//【重要】使用cglib实例化对象
return instantiateWithMethodInjection(bd, beanName, owner);
}
}

DefaultSingletonBeanRegistry#addSingletonFactory方法

查看代码
    /**
* 向三级缓存添加bean实例
*/
protected void addSingletonFactory(String beanName, ObjectFactory<?> singletonFactory) {
Assert.notNull(singletonFactory, "Singleton factory must not be null");
synchronized (this.singletonObjects) {
if (!this.singletonObjects.containsKey(beanName)) {
this.singletonFactories.put(beanName, singletonFactory);
this.earlySingletonObjects.remove(beanName);
this.registeredSingletons.add(beanName);
}
}
}

AbstractAutowireCapableBeanFactory#initializeBean方法

查看代码
/**
* 初始化容器创建的bean实例对象,为其添加BeanPostProcessor后置处理器
* 调用Aware接口方法 -> 调用BeanPostProcessor.before方法 -> 调用init-method方法 -> 调用BeanPostProcessor.after方法
*/
protected Object initializeBean(final String beanName, final Object bean, @Nullable RootBeanDefinition mbd) {
// 通过JDK的安全机制验证权限
if (System.getSecurityManager() != null) {
// 实现PrivilegedAction接口的匿名内部类
AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
invokeAwareMethods(beanName, bean);
return null;
}, getAccessControlContext());
}
else {
// 为bean实例对象包装相关属性,如名称、类加载器、所属容器等
invokeAwareMethods(beanName, bean);
} Object wrappedBean = bean;
// 调用BeanPostProcessor后置处理器的回调方法,在bean实例初始化前做一些处理
if (mbd == null || !mbd.isSynthetic()) {
wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
} try {
// 调用init方法
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后置处理器的回调方法,在bean实例初始化后做一些处理
wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
} return wrappedBean;
}

到此,我们看完了bean创建的完整过程。

参考资料:

《Spring5核心原理与30个类手写》作者 谭勇德

《Spring源码深度解析》作者 郝佳

《Spring技术内幕》作者 计文柯

Spring源码-IOC部分-Bean实例化过程【5】的更多相关文章

  1. Spring源码-IOC部分-容器初始化过程【2】

    实验环境:spring-framework-5.0.2.jdk8.gradle4.3.1 Spring源码-IOC部分-容器简介[1] Spring源码-IOC部分-容器初始化过程[2] Spring ...

  2. Spring Ioc源码分析系列--Bean实例化过程(一)

    Spring Ioc源码分析系列--Bean实例化过程(一) 前言 上一篇文章Spring Ioc源码分析系列--Ioc容器注册BeanPostProcessor后置处理器以及事件消息处理已经完成了对 ...

  3. Spring Ioc源码分析系列--Bean实例化过程(二)

    Spring Ioc源码分析系列--Bean实例化过程(二) 前言 上篇文章Spring Ioc源码分析系列--Bean实例化过程(一)简单分析了getBean()方法,还记得分析了什么吗?不记得了才 ...

  4. Spring 源码分析之 bean 实例化原理

    本次主要想写spring bean的实例化相关的内容.创建spring bean 实例是spring bean 生命周期的第一阶段.bean 的生命周期主要有如下几个步骤: 创建bean的实例 给实例 ...

  5. 【转载】Spring 源码分析之 bean 实例化原理

    本次主要想写spring bean的实例化相关的内容.创建spring bean 实例是spring bean 生命周期的第一阶段.bean 的生命周期主要有如下几个步骤: 创建bean的实例 给实例 ...

  6. Spring源码-IOC部分-Spring是如何解决Bean循环依赖的【6】

    实验环境:spring-framework-5.0.2.jdk8.gradle4.3.1 Spring源码-IOC部分-容器简介[1] Spring源码-IOC部分-容器初始化过程[2] Spring ...

  7. Spring源码-IOC部分-Xml Bean解析注册过程【3】

    实验环境:spring-framework-5.0.2.jdk8.gradle4.3.1 Spring源码-IOC部分-容器简介[1] Spring源码-IOC部分-容器初始化过程[2] Spring ...

  8. Spring源码-IOC部分-自定义IOC容器及Bean解析注册【4】

    实验环境:spring-framework-5.0.2.jdk8.gradle4.3.1 Spring源码-IOC部分-容器简介[1] Spring源码-IOC部分-容器初始化过程[2] Spring ...

  9. Spring源码-IOC部分-容器简介【1】

    实验环境:spring-framework-5.0.2.jdk8.gradle4.3.1 Spring源码-IOC部分-容器简介[1] Spring源码-IOC部分-容器初始化过程[2] Spring ...

随机推荐

  1. 【LeetCode】102. Binary Tree Level Order Traversal 二叉树的层序遍历 (Python&C++)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客:http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 BFS DFS 日期 题目地址:https://lee ...

  2. Description has only two Sentences(hdu3307)

    Description has only two Sentences Time Limit: 3000/1000 MS (Java/Others)    Memory Limit: 65536/327 ...

  3. html基础 字符实体 用于html中特殊符号的展示 比如:多个空格、代码展示

    结构:&+英文: 常见的字符实体  

  4. hisql 高级功能数据检测将错误数据拦截在系统外 一

    hisql github源码下载 git clone https://github.com/tansar/HiSql.git 在设计第二范式数据库时经常会把可能重复的数据单独做一种表关联,但是在写入表 ...

  5. nginx高并发配置详解

    https://www.cnblogs.com/liqiu/p/3152206.html 1.  worker_processes 8; nginx 进程数,建议按照cpu 数目来指定,一般为它的倍数 ...

  6. [ unittest ] 使用初体验

    import unittest from cal import Calculate class Mytest(unittest.TestCase): def setUp(self): self.cal ...

  7. VM搭建Hadoop环境遇到的问题

    原文链接:https://www.toutiao.com/i6482644128860471822/ 一.Slave2中sshd服务一直处于启动失败状态 查看配置文件 c 发现配置文件末尾slave2 ...

  8. BitMap算法知识笔记以及在大数据方向的使用

    概述 所谓的BitMap算法就是位图算法,简单说就是用一个bit位来标记某个元素所对应的value,而key即是该元素,由于BitMap使用了bit位来存储数据,因此可以大大节省存储空间,这是很常用的 ...

  9. redis的bind误区

    对于Redis中bind的正确的理解是:bind:是绑定本机的IP地址,(准确的是:本机的网卡对应的IP地址,每一个网卡都有一个IP地址),而不是redis允许来自其他计算机的IP地址.如果指定了bi ...

  10. openGL绘图基本框架

    openGL绘图入门和导入外部文件 本文主要介绍通用绘图软件openGL的数据类型和基本的绘图框架,此外还提供了导入obj外部文件的方法,提供的代码稍作修改即可使用,希望能方便初学者快速上手. ope ...