目录
一、整体流程
二、流程分解
流程分为四个部分,分别是实例化、属性赋值、初始化、销毁
创建Bean的核心代码是AbstractAutowireCapableBeanFactory#createBean
2.1 createBean
在真正创建Bean之前,会先resolveBeforeInstantiation判断是否存在自定义创建bean,如没有,框架再去新创建一个。核心代码都在doCreateBean
中,doCreateBean是才是真正创建Bean的地方。
protected Object createBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)
throws BeanCreationException {
.......代码省略
try {
/** 在实例化之前判断该bean有没有被自定义创建
* 根据InstantiationAwareBeanPostProcessors实现类的
* applyBeanPostProcessorsBeforeInstantiation方法判断
* 返回值不是null,表示已被自定义创建
**/
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 {
// 创建bean的核心代码
Object beanInstance = doCreateBean(beanName, mbdToUse, args);
if (logger.isTraceEnabled()) {
logger.trace("Finished creating instance of bean '" + beanName + "'");
}
return beanInstance;
}
.......代码省略
}
resolveBeforeInstantiation:
applyBeanPostProcessorsBeforeInstantiation
:获取所有InstantiationAwareBeanPostProcessor的实现类,执行postProcessBeforeInstantiation方法,如果该方法返回的对象不是null,则表示自定义指定bean,不再执行doCreateBean,并且会执行applyBeanPostProcessorsAfterInitialization方法设置bean。
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 = applyBeanPostProcessorsBeforeInstantiation(targetType, beanName);
if (bean != null) {
bean = applyBeanPostProcessorsAfterInitialization(bean, beanName);
}
}
}
mbd.beforeInstantiationResolved = (bean != null);
}
return bean;
}
2.2 doCreateBean
先总看一下doCreateBean的源码有哪些主要点,然后再逐个分解,主要的点有:(1)实例化bean(createBeanInstance)、(2)MergedBeanDefinitionPostProcessor初始化之前修改BeanDefinition的扩展点(比如扫描@Autowired)、(3)出现循环依赖提前暴露bean、(4)属性赋值(populateBean)、(5)初始化(initializeBean)、(6)判断在初始化的过程后bean是否还是原来的bean
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
instanceWrapper = createBeanInstance(beanName, mbd, args);
}
final Object bean = instanceWrapper.getWrappedInstance();
Class<?> beanType = instanceWrapper.getWrappedClass();
if (beanType != NullBean.class) {
mbd.resolvedTargetType = beanType;
}
synchronized (mbd.postProcessingLock) {
if (!mbd.postProcessed) {
try {
// 可以修改BeanDefinition的扩展点,可以初始化之前做一些工作,比如扫描一些属性的注解
// CommonAnnotationBeanPostProcessor -> @PostConstruct @PreDestroy @Resource
// AutowiredAnnotationBeanPostProcessor -> @Autowired @Value
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,可以称为半成品的bean或实例化bean
// getEarlyBeanReference方法中执行SmartInstantiationAwareBeanPostProcessor的getEarlyBeanReference方法
// getEarlyBeanReference中可以对bean做一些操作,主要应用是Aop织入
// 对循环依赖感兴趣的话可以去看我的另一篇关于循环依赖的文章。
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");
}
// 提前暴露bean的获取
addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean));
}
Object exposedObject = bean;
try {
// 属性赋值
populateBean(beanName, mbd, instanceWrapper);
// 初始化bean
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) {
Object earlySingletonReference = getSingleton(beanName, false);
// 出现循环依赖的时候earlySingletonReference才不为null
if (earlySingletonReference != null) {
// 这里判断在初始化的过程中,bean是否还是原来的bean,如果不是就会在下面的分支中报错
if (exposedObject == bean) {
exposedObject = earlySingletonReference;
}
else if (!this.allowRawInjectionDespiteWrapping && hasDependentBean(beanName)) {
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.");
}
}
}
}
// 注册到 disposableBeans 里面.
try {
registerDisposableBeanIfNecessary(beanName, bean, mbd);
}
catch (BeanDefinitionValidationException ex) {
throw new BeanCreationException(
mbd.getResourceDescription(), beanName, "Invalid destruction signature", ex);
}
return exposedObject;
}
2.3 实例化(createBeanInstance)
从这节开始到最后一节之前,讲的都是doCreateBean中的内容。
createBeanInstance: 提供了几种实例化bean的方式和扩展点。
-
instanceSupplier: 作为首选方式,用回调函数创建bean可以避免因使用反射而造成的性能丢失。因为工厂方法或者静态工厂创建bean都要用到反射。
-
工厂方法:在定义bean的时候,自定义factory-method属性,指定创建bean的工厂方法。
-
指定构造器创建:实现SmartInstantiationAwareBeanPostProcessor接口的determineCandidateConstructors指定构造器。
-
无参构造创建: 默认方式,获取beanClass文件的无参构造,反射创建。
protected BeanWrapper createBeanInstance(String beanName, RootBeanDefinition mbd, @Nullable Object[] args) {
// Make sure bean class is actually resolved at this point.
Class<?> beanClass = resolveBeanClass(mbd, beanName);
// 利用提供的回调函数创建bean
Supplier<?> instanceSupplier = mbd.getInstanceSupplier();
if (instanceSupplier != null) {
return obtainFromSupplier(instanceSupplier, beanName);
}
// 利用自定义的factory-method方法创建bean
if (mbd.getFactoryMethodName() != null) {
return instantiateUsingFactoryMethod(beanName, mbd, args);
}
.....代码省略
// 判断是否有设置BeanPostProcessor指定构造器
Constructor<?>[] ctors = determineConstructorsFromBeanPostProcessors(beanClass, beanName);
if (ctors != null || mbd.getResolvedAutowireMode() == AUTOWIRE_CONSTRUCTOR ||
mbd.hasConstructorArgumentValues() || !ObjectUtils.isEmpty(args)) {
return autowireConstructor(beanName, mbd, ctors, args);
}
.....代码省略
// 没有特别处理,默认使用无参构造创建bean,默认执行instantiateBean
return instantiateBean(beanName, mbd);
}
2.4 MergedBeanDefinitionPostProcessor扩展点
实现MergedBeanDefinitionPostProcessor接口,对BeanDefinition做出来,比如实现类AutowiredAnnotationBeanPostProcessor,用于扫描@Autowired和@Value注解。
protected void applyMergedBeanDefinitionPostProcessors(RootBeanDefinition mbd, Class<?> beanType, String beanName) {
for (BeanPostProcessor bp : getBeanPostProcessors()) {
if (bp instanceof MergedBeanDefinitionPostProcessor) {
MergedBeanDefinitionPostProcessor bdp = (MergedBeanDefinitionPostProcessor) bp;
bdp.postProcessMergedBeanDefinition(mbd, beanType, beanName);
}
}
}
2.5 属性赋值(populateBean)
这个方法中是对自定义对象属性的赋值,比如自定义的User类等等。
方法步骤:
- 执行InstantiationAwareBeanPostProcessors的后置处理器
- CommonAnnotationBeanPostProcessor处理@Resource标注的属性
- AutowiredAnnotationBeanPostProcessor处理@Autowired、@Value标注的属性
- 绑定属性值
protected void populateBean(String beanName, RootBeanDefinition mbd, @Nullable BeanWrapper bw) {
.....代码省略
/**
* 执行InstantiationAwareBeanPostProcessors的后置处理器
* 如果postProcessAfterInstantiation返回false,不再继续执行populateBean,但对后续处理没有影响
*/
if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
for (BeanPostProcessor bp : getBeanPostProcessors()) {
if (bp instanceof InstantiationAwareBeanPostProcessor) {
InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
if (!ibp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) {
return;
}
}
}
}
PropertyValues pvs = (mbd.hasPropertyValues() ? mbd.getPropertyValues() : null);
// 自动注入模式,默认resolvedAutowireMode == AUTOWIRE_NO
int resolvedAutowireMode = mbd.getResolvedAutowireMode();
if (resolvedAutowireMode == AUTOWIRE_BY_NAME || resolvedAutowireMode == AUTOWIRE_BY_TYPE) {
MutablePropertyValues newPvs = new MutablePropertyValues(pvs);
// Add property values based on autowire by name if applicable.
if (resolvedAutowireMode == AUTOWIRE_BY_NAME) {
autowireByName(beanName, mbd, bw, newPvs);
}
// Add property values based on autowire by type if applicable.
if (resolvedAutowireMode == AUTOWIRE_BY_TYPE) {
autowireByType(beanName, mbd, bw, newPvs);
}
pvs = newPvs;
}
boolean hasInstAwareBpps = hasInstantiationAwareBeanPostProcessors();
boolean needsDepCheck = (mbd.getDependencyCheck() != AbstractBeanDefinition.DEPENDENCY_CHECK_NONE);
PropertyDescriptor[] filteredPds = null;
if (hasInstAwareBpps) {
if (pvs == null) {
pvs = mbd.getPropertyValues();
}
/**
* 这里有两个重要的BeanPostProcessors实现
* 1. CommonAnnotationBeanPostProcessor: 处理@Resource标注的属性
* 2. AutowiredAnnotationBeanPostProcessor:处理@Autowired、@Value标注的属性
*/
for (BeanPostProcessor bp : getBeanPostProcessors()) {
if (bp instanceof InstantiationAwareBeanPostProcessor) {
InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
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 (pvs != null) {
// 属性绑定
applyPropertyValues(beanName, mbd, bw, pvs);
}
}
2.6 初始化(initializeBean)
执行Aware接口对bean中的工厂对象属性赋值、执行创建Aop的扩展点等等、执行初始化方法
-
invokeAwareMethods: 执行bean实现的BeanNameAware、BeanClassLoaderAware和BeanFactoryAware接口的方法
-
applyBeanPostProcessorsBeforeInitialization: 执行所有BeanPostProcessor的前置处理器, 属于spring的扩展点,其中重要的有
ApplicationContextAwareProcessor
,用于执行bean实现的EnvironmentAware、ApplicationContextAware等Aware接口的方法 -
invokeInitMethods: 执行初始化方法
init-method
和afterPropertiesSet
-
applyBeanPostProcessorsAfterInitialization: 执行所有BeanPostProcessor的后置处理器,属于spring的扩展点,其中Aop就是在这里实现的,下一大节会讲述。
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 {
// 执行bean实现BeanNameAware、BeanClassLoaderAware、BeanFactoryAware的方法
invokeAwareMethods(beanName, bean);
}
Object wrappedBean = bean;
if (mbd == null || !mbd.isSynthetic()) {
// 执行所有BeanPostProcessor的前置处理器
// 其中重要的有ApplicationContextAwareProcessor,用于执行bean实现EnvironmentAware、ApplicationContextAware等等Aware接口的方法
wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
}
try {
// 执行初始化方法init-method和afterPropertiesSet
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的后置处理器
wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
}
return wrappedBean;
}
invokeInitMethods:
protected void invokeInitMethods(String beanName, final Object bean, @Nullable RootBeanDefinition mbd)
throws Throwable {
// 判断是否实现了InitializingBean接口
boolean isInitializingBean = (bean instanceof InitializingBean);
if (isInitializingBean && (mbd == null || !mbd.isExternallyManagedInitMethod("afterPropertiesSet"))) {
if (logger.isTraceEnabled()) {
logger.trace("Invoking afterPropertiesSet() on bean with name '" + beanName + "'");
}
if (System.getSecurityManager() != null) {
try {
AccessController.doPrivileged((PrivilegedExceptionAction<Object>) () -> {
((InitializingBean) bean).afterPropertiesSet();
return null;
}, getAccessControlContext());
}
catch (PrivilegedActionException pae) {
throw pae.getException();
}
}
else {
// 执行afterPropertiesSet
((InitializingBean) bean).afterPropertiesSet();
}
}
if (mbd != null && bean.getClass() != NullBean.class) {
String initMethodName = mbd.getInitMethodName();
// 判断是否有init-method
if (StringUtils.hasLength(initMethodName) &&
!(isInitializingBean && "afterPropertiesSet".equals(initMethodName)) &&
!mbd.isExternallyManagedInitMethod(initMethodName)) {
invokeCustomInitMethod(beanName, bean, mbd);
}
}
}
2.7 SmartInitializingSingleton扩展点
主要用于在IoC容器基本启动完成时进行扩展,这时非Lazy的Singleton都已被初始化完。
最后一步,bean创建完毕之后,如果bean实现了SmartInitializingSingleton接口,则执行afterSingletonsInstantiated()。这个是getBean()之后执行的。
// Trigger post-initialization callback for all applicable beans...
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();
}
}
}
三、在BeanPostProcessor中实现的Aop
在众多BeanPostProcessor的实现类中,有个名字很熟悉的实现类AbstractAutoProxyCreator。
看下它的后置处理方法,其中有个关于earlyProxyReferences的判断,这个是和循环依赖有关系,顺带提一嘴,在循环依赖中bean如果需要创建代理,不在这创建代理对象,而是在实例化的时候就要把代理对象创建出来,这里是为了防止重复创建代理对象才设置的判断。
public Object postProcessAfterInitialization(@Nullable Object bean, String beanName) {
if (bean != null) {
Object cacheKey = getCacheKey(bean.getClass(), beanName);
if (this.earlyProxyReferences.remove(cacheKey) != bean) {
return wrapIfNecessary(bean, beanName, cacheKey);
}
}
return bean;
}
wrapIfNecessary:
言归正传,可以看出wrapIfNecessary才是真正创建代理的方法。
在这个方法中我们会发现一个眼熟的方法createProxy
,代理对象在这个方法中创建并返回。
protected Object wrapIfNecessary(Object bean, String beanName, Object cacheKey) {
if (StringUtils.hasLength(beanName) && this.targetSourcedBeans.contains(beanName)) {
return bean;
}
if (Boolean.FALSE.equals(this.advisedBeans.get(cacheKey))) {
return bean;
}
if (isInfrastructureClass(bean.getClass()) || shouldSkip(bean.getClass(), beanName)) {
this.advisedBeans.put(cacheKey, Boolean.FALSE);
return bean;
}
// Create proxy if we have advice.
Object[] specificInterceptors = getAdvicesAndAdvisorsForBean(bean.getClass(), beanName, null);
if (specificInterceptors != DO_NOT_PROXY) {
this.advisedBeans.put(cacheKey, Boolean.TRUE);
Object proxy = createProxy(
bean.getClass(), beanName, specificInterceptors, new SingletonTargetSource(bean));
this.proxyTypes.put(cacheKey, proxy.getClass());
return proxy;
}
this.advisedBeans.put(cacheKey, Boolean.FALSE);
return bean;
}
四、总结
生命周期步骤:
- 【实例化 - doCreateBean前】执行InstantiationAwareBeanPostProcessors的前置处理器,判断是否有已经指定创建好的对象。
- 【实例化 - createBeanInstance】选择实例化的方式,如回调函数、工厂方法、指定构造器等等。
- 【实例化 - createBeanInstance】无特别处理使用默认无参构造实例化(instantiateBean)。
- 【实例化 - createBeanInstance后】利用MergedBeanDefinitionPostProcessor扩展点修改BeanDefinition的定义信息。
- 【属性赋值 - populateBean前】执行InstantiationAwareBeanPostProcessors的后置处理器,一般用于自定义属性赋值。
- 【属性赋值 - populateBean】CommonAnnotationBeanPostProcessor: 处理@Resource标注的属性。
- 【属性赋值 - populateBean】AutowiredAnnotationBeanPostProcessor:处理@Autowired、@Value标注的属性。
- 【初始化 - initializeBean】invokeAwareMethods,执行bean实现BeanNameAware、BeanClassLoaderAware和BeanFactoryAware接口的方法。
- 【初始化 - initializeBean】执行所有BeanPostProcessor的前置处理器,其中重要的有ApplicationContextAwareProcessor,用于执行bean实现EnvironmentAware、ApplicationContextAware等等Aware接口的方法。
- 【初始化 - initializeBean】执行初始化方法init-method和afterPropertiesSet。
- 【初始化 - initializeBean】执行所有BeanPostProcessor的后置处理器。
- 【基本创建完毕后】执行SmartInitializingSingleton扩展点。