原文网址:Bean生命周期--Bean的创建过程_IT利刃出鞘的博客-CSDN博客
说明
Spring的核心模块是IOC和AOP,而IOC中创建Bean又是十分重要的一环。在Spring的启动过程中,会在refresh()方法中调用finishBeanFactoryInitialization()。在finishBeanFactoryInitialization中完成了非懒加载的单例bean的创建。所以要搞清楚bean的创建过程,就要从finishBeanFactoryInitialization()方法的源码入手。
总体流程
AbstractApplicationContext#refresh()
finishBeanFactoryInitialization(beanFactory); //AbstractApplicationContext抽象类
beanFactory.preInstantiateSingletons(); //DefaultListableBeanFactory类。(实现的ConfigurableListableBeanFactory接口)
preInstantiateSingletons() //DefaultListableBeanFactory类。(实现的ConfigurableListableBeanFactory接口)
getBean(beanName) //AbstractBeanFactory抽象类(实现的BeanFactory接口)
doGetBean(name, null, null, false) //AbstractBeanFactory抽象类。自己的方法。
// 先从单例的缓存中取,取不到则创建,下边只展示缓存中没有而进行创建时的流程。
createBean(beanName, mbd, args) //AbstractAutowireCapableBeanFactory抽象类(实现的AbstractBeanFactory)
doCreateBean(beanName, mbdToUse, args)//AbstractAutowireCapableBeanFactory抽象类。以下为此类方法
createBeanInstance(beanName, mbd, args); //创建实例
applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName) //post-processors修改bean的定义
addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean)); //解决循环依赖
populateBean(beanName, mbd, instanceWrapper); //填充属性
initializeBean(beanName, exposedObject, mbd); //初始化bean
位于:AbstractApplicationContext抽象类。
概述
该方法十分重要,它完成了所有非懒加载的单例Bean的实例化和初始化,属性的填充以及解决了循环依赖等问题。
这里特意将对象的实例化和初始化过程分开了,因为在Spring创建Bean的过程中,是先将Bean通过反射创建对象,然后通过后置处理器(BeanPostProcessor)来为对象的属性赋值。所以这里的实例化时指将Bean创建出来,初始化是指为bean的属性赋值。
源码
finishBeanFactoryInitialization()方法的代码如下,bean的创建和初始化均在beanFactory.preInstantiateSingletons()中实现。
protected void finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory) {
// 初始化转换服务
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,那么在这儿会注册一个内置的属性后置处理器
// 这儿主要是处理被加了注解的属性
if (!beanFactory.hasEmbeddedValueResolver()) {
beanFactory.addEmbeddedValueResolver(strVal -> getEnvironment().resolvePlaceholders(strVal));
}
// Initialize LoadTimeWeaverAware beans early to allow for registering their transformers early.
String[] weaverAwareNames = beanFactory.getBeanNamesForType(LoadTimeWeaverAware.class, false, false);
for (String weaverAwareName : weaverAwareNames) {
getBean(weaverAwareName);
}
beanFactory.setTempClassLoader(null);
// 将BeanFactory的configurationFrozen属性设置为true,给frozenBeanDefinitionNames属性赋值
// 目的是为了不让在其他的地方在修改bean的BeanDefinition
beanFactory.freezeConfiguration();
// Instantiate all remaining (non-lazy-init) singletons.
// 实例化剩下所有的非懒加载的单例
beanFactory.preInstantiateSingletons();
}
位于:DefaultListableBeanFactory类。(实现的ConfigurableListableBeanFactory接口)
概述
该方法会先判断bean是否是一个FactoryBean,以及是否立即实例化FactoryBean的getObject()返回的对象,但最终均是调用getBean()方法去实例化对象。在Bean实例化、初始化完成后,会判断Bean是否实现了SmartSingletonInitializing接口,如果实现了,则会调用该接口的afterSingletonInstantiated()方法。
Tips:这里提到了FactoryBean,不是BeanFactory。这两者名字很像,但作用却是天差地别。后续会单独写一篇文章介绍FactoryBean,并通过FactoryBean去解析Spring与MyBatis整合的原理。
FactoryBean是一个接口,该接口的实现类会向容器中注册两个bean,一个是实现类本身所代表类型的对象,一个是通过重写FactoryBean接口中getObject()方法所返回的bean。如下例子中:会向容器中注册两个bean,一个是MapperFactoryBean本身,一个是UserMapper。
@Component
public class MapperFactoryBean implements FactoryBean {
@Override
public Object getObject() throws Exception {
return new UserMapper();
}
@Override
public Class> getObjectType() {
return UserMapper.class;
}
}
由于bean的实例化过程太过复杂,后面会结合流程图去分析源码。preInstantiatedSingletons()方法的执行流程图如下
不论是FactoryBean还是普通Bean,最终都是调用getBean()方法去创建bean。
源码
public void preInstantiateSingletons() throws BeansException {
if (logger.isDebugEnabled()) {
logger.debug("Pre-instantiating singletons in " + this);
}
List beanNames = new ArrayList<>(this.beanDefinitionNames);
// Trigger initialization of all non-lazy singleton beans...
for (String beanName : beanNames) {
RootBeanDefinition bd = getMergedLocalBeanDefinition(beanName);
if (!bd.isAbstract() && bd.isSingleton() && !bd.isLazyInit()) {
// 判断是否是factoryBean,如果是FactoryBean,则进行FactoryBean原生的实例化(非getObject()方法对应的对象)。
// 还需要判断它是否立即实例化getObject()返回的对象,根据SmartFactoryBean的isEagerInit()的返回值判断是否需要立即实例化
if (isFactoryBean(beanName)) {
// 首先实例化BeanFactory的原生对象,然后再根据isEagerInit()判断是否实例化BeanFactory中getObject()返回的类型的对象
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)
((SmartFactoryBean>) factory)::isEagerInit,
getAccessControlContext());
} else {
isEagerInit = (factory instanceof SmartFactoryBean &&
((SmartFactoryBean>) factory).isEagerInit());
}
// 如果isEagerInit为true,则立即实例化FactoryBean所返回的类型的对象
if (isEagerInit) {
getBean(beanName);
}
}
} else {
getBean(beanName);
}
}
}
// 在bean实例化以及属性赋值完成后,如果bean实现了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
位于:AbstractBeanFactory抽象类(实现的BeanFactory接口)
概述
调用doGetBean(name, null, null, false) //AbstractBeanFactory抽象类。自己的方法
源码
public Object getBean(String name) throws BeansException {
return doGetBean(name, null, null, false);
}
位于:AbstractBeanFactory抽象类。自己的方法
概述
doGetBean 中有两个 getSingleton 方法会先后执行,本文用 getSingleton-C 和 getSingleton-F 来区分。第一个是尝试从缓存中获取,若缓存中没有 A,则执行第二个,通过工厂获得。
public Object getSingleton(String beanName) //简记为:getSingleton-C。
public Object getSingleton(String beanName, ObjectFactory> singletonFactory) //简记为:getSingleton-F。
源码
doGetBean()方法代码如下
protected T doGetBean(final String name, @Nullable final Class requiredType,
@Nullable final Object[] args, boolean typeCheckOnly) throws BeansException {
final String beanName = transformedBeanName(name);
Object bean;
// Eagerly check singleton cache for manually registered singletons.
Object sharedInstance = getSingleton(beanName);
if (sharedInstance != null && args == null) {
bean = getObjectForBeanInstance(sharedInstance, name, beanName, null);
}
else {
// Fail if we're already creating this bean instance:
// We're assumably within a circular reference.
if (isPrototypeCurrentlyInCreation(beanName)) {
throw new BeanCurrentlyInCreationException(beanName);
}
// Check if bean definition exists in this factory.
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 {
return parentBeanFactory.getBean(nameToLookup, requiredType);
}
}
if (!typeCheckOnly) {
// 标记bean为已创建
// 并清除beanDefinition的缓存(mergedBeanDefinitions)
markBeanAsCreated(beanName);
}
try {
final RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
// 检查bean是否是抽象类
checkMergedBeanDefinition(mbd, beanName, args);
// Guarantee initialization of beans that the current bean depends on.
// 保证当前bean所依赖的bean初始化
String[] dependsOn = mbd.getDependsOn();
if (dependsOn != null) {
for (String dep : dependsOn) {
// isDependent()方法用来判断dep是否依赖beanName
if (isDependent(beanName, dep)) {
throw new BeanCreationException(mbd.getResourceDescription(), beanName,
"Circular depends-on relationship between '" + beanName + "' and '" + dep + "'");
}
// 保存下依赖关系
registerDependentBean(dep, beanName);
try {
getBean(dep);
}
catch (NoSuchBeanDefinitionException ex) {
throw new BeanCreationException(mbd.getResourceDescription(), beanName,
"'" + beanName + "' depends on missing bean '" + dep + "'", ex);
}
}
}
// Create bean instance.
if (mbd.isSingleton()) {
// 此时在getSingleton方法中传入了一个lambda表达式,
// 此时不会立即执行lambda表达式,而是在调用这个lambda表达式的getObject()方法时才开始执行lambda的方法体
sharedInstance = getSingleton(beanName, () -> {
try {
return createBean(beanName, mbd, args);
}
catch (BeansException ex) {
destroySingleton(beanName);
throw ex;
}
});
bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
}
else if (mbd.isPrototype()) {
// It's a prototype -> create a new instance.
Object prototypeInstance = null;
try {
beforePrototypeCreation(beanName);
prototypeInstance = createBean(beanName, mbd, args);
}
finally {
afterPrototypeCreation(beanName);
}
bean = getObjectForBeanInstance(prototypeInstance, name, beanName, mbd);
}
else {
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;
}
}
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) {
throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass());
}
}
return (T) bean;
}
getObjectForBeanInstance()方法的作用是为了根据beanName来判断是返回FactoryBean原生对象还是getObject()方法所返回的对象.若beanName以&符号开头,则表示返回FactoryBean原生对象,否则返回getObject()方法所返回的对象。
protected Object getObjectForBeanInstance(
Object beanInstance, String name, String beanName, @Nullable RootBeanDefinition mbd) {
if (BeanFactoryUtils.isFactoryDereference(name)) {
if (beanInstance instanceof NullBean) {
return beanInstance;
}
if (!(beanInstance instanceof FactoryBean)) {
throw new BeanIsNotAFactoryException(transformedBeanName(name), beanInstance.getClass());
}
}
// 如果不是一个FactoryBean对象或者是获取FactoryBean的原生对象(原生对象指的是beanName是以&开头)
// 此时可以直接返回bean
if (!(beanInstance instanceof FactoryBean) || BeanFactoryUtils.isFactoryDereference(name)) {
return beanInstance;
}
// 如果是获取FactoryBean的getObject()方法返回的类型对象,则需要进入到如下逻辑
// 对于getObject()方法,它返回的对象是在在第一次调用getObject方法时进行实例化的,实例化完成以后,会将结果缓存在factoryBeanObjectCache中
Object object = null;
if (mbd == null) {
object = getCachedObjectForFactoryBean(beanName);
}
if (object == null) {
// Return bean instance from factory.
FactoryBean> factory = (FactoryBean>) beanInstance;
// Caches object obtained from FactoryBean if it is a singleton.
if (mbd == null && containsBeanDefinition(beanName)) {
mbd = getMergedLocalBeanDefinition(beanName);
}
boolean synthetic = (mbd != null && mbd.isSynthetic());
// 获取FactoryBean返回的对象
object = getObjectFromFactoryBean(factory, beanName, !synthetic);
}
return object;
}
位于:AbstractAutowireCapableBeanFactory抽象类(实现的AbstractBeanFactory)
概述
doGetBean()最终会调用createBean()来创建bean。
createBean()方法的代码中,主要有两行核心代码:
Object bean = resolveBeforeInstantiation(beanName, mbdToUse);
Object beanInstance = doCreateBean(beanName, mbdToUse, args);
createBean()方法的流程图
resolveBeforeInstantiation()
createBean()方法的源代码
protected Object createBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)
throws BeanCreationException {
RootBeanDefinition mbdToUse = mbd;
// Make sure bean class is actually resolved at this point, and
// clone the bean definition in case of a dynamically resolved Class
// which cannot be stored in the shared merged bean definition.
Class> resolvedClass = resolveBeanClass(mbd, beanName);
if (resolvedClass != null && !mbd.hasBeanClass() && mbd.getBeanClassName() != null) {
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 {
// Give BeanPostProcessors a chance to return a proxy instead of the target bean instance.
// 第一次调用后置处理器(执行所有InstantiationAwareBeanPostProcessor的子类)
// 如果InstantiationAwareBeanPostProcessor的子类的postProcessBeforeInstantiation()方法返回值不为空,表示bean需要被增强,
// 此时将不会执行后面的逻辑,AOP的实际应用就是在这儿实现的
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.isDebugEnabled()) {
logger.debug("Finished creating instance of bean '" + beanName + "'");
}
return beanInstance;
}
catch (BeanCreationException | ImplicitlyAppearedSingletonException ex) {
throw ex;
}
catch (Throwable ex) {
throw new BeanCreationException(
mbdToUse.getResourceDescription(), beanName, "Unexpected exception during bean creation", ex);
}
}
位于:AbstractAutowireCapableBeanFactory抽象类。自己的方法。
流程图
描述
doCreateBean()方法的代码
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) {
// 实例化bean(第二次执行后置处理器的入口),第二次执行后置处理器,主要是为了推断出实例化Bean所需要的构造器
instanceWrapper = createBeanInstance(beanName, mbd, args);
}
final Object bean = instanceWrapper.getWrappedInstance();
Class> beanType = instanceWrapper.getWrappedClass();
if (beanType != NullBean.class) {
mbd.resolvedTargetType = beanType;
}
// 此时bean对象已经创建成功,但是没有设置属性和经过其他后置处理器处理
// Allow post-processors to modify the merged bean definition.
synchronized (mbd.postProcessingLock) {
if (!mbd.postProcessed) {
try {
// 第三次执行后置处理器,缓存bean的注解元数据信息(用于后面在进行属性填充时使用)
// 这一步对于CommonAnnotationBeanPostProcessor、AutowiredAnnotationBeanPostProcessor、
// RequiredAnnotationBeanPostProcessor这一类处理器
// 主要是将bean的注解信息解析出来,然后缓存到后置处理器中的injectionMetadataCache属性中
// ApplicationListenerDetector将bean是否是单例的标识存于singletonNames这个Map类型的属性中
applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);
}
mbd.postProcessed = true;
}
}
// 判断一个bean是否放入到singletonFactories中(提前暴露出来,可以解决循环依赖的问题)
boolean earlySingletonExposure = (mbd.isSingleton() && this.allowCircularReferences &&
isSingletonCurrentlyInCreation(beanName));
if (earlySingletonExposure) {
// 第四次出现后置处理器
// 获取提前暴露的对象,可以解决循环引用的问题,实际上提前暴露出来的bean是放入到了singletonFactories中,
// key是beanName,value是一个lambda表达式
addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean));
}
// Initialize the bean instance.
Object exposedObject = bean;
try {
// 填充属性,第五次、第六次后置处理器入口
populateBean(beanName, mbd, instanceWrapper);
// 第七次、第八次执行后置处理器入口
exposedObject = initializeBean(beanName, exposedObject, mbd);
}
catch (Throwable ex) {
}
return exposedObject;
}
通过源码看Bean的创建过程