spring之Bean实例化过程
一、概述
spring初始化Bean的流程比较复杂,除了普通的构造函数实例化Bean之外,spring还支持工厂模式创建Bean(即常说的Factory Bean)。在spring实例化完Bean之后,会进行Bean的一些初始化工作。其中涉及到扩展点调用、运行时类型成员解析、依赖注入、懒加载等流程,还解决了循环引用、类型转换等问题。熟悉Bean加载的过程,开发过程中选择扩展点时就可以做到游刃有余。为了更加关注逻辑流程,本文所贴的代码精简掉了不相关的部分。
二、Bean实例化概要流程
1.获取Bean过程中涉及到的扩展点
org.springframework.beans.factory.support.MethodOverride
org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessor
org.springframework.beans.factory.support.MergedBeanDefinitionPostProcessor
org.springframework.beans.factory.config.BeanPostProcessor
org.springframework.beans.factory.InitializingBean
2.关键方法框架图
org.springframework.beans.factory.support.AbstractBeanFactory.doGetBeanorg.springframework.beans.factory.support.AbstractBeanFactory.getObjectForBeanInstance
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean
三、Bean实例化详细流程
1.相关入口
- 根据类型获取Bean
org.springframework.context.support.AbstractApplicationContext.getBean(Class<T>)- 根据名字获取Bean
org.springframework.context.support.AbstractApplicationContext.getBean(String)- 实际获取Bean
org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean- 根据给出的Bean获取真实Bean(可能是factoryBean)
org.springframework.beans.factory.support.AbstractBeanFactory.getObjectForBeanInstance- 创建Bean
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean- 实际创建Bean
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean
2.详细解析
除了单例且非懒加载的Bean是在ApplicationContext刷新的时候初始化之外。其他Bean都是在使用的时候才会加载,即我们常用的getBean方法。这个方法提供了很多重载,总的类型只有两种:
- 根据类型获取Bean
- 根据Name获取Bean
两种类型最终内部都调用到了同一个方法,详见下述伪代码:
-------------------- 根据类型获取Bean最终调用的是doGetBean方法
-- org.springframework.context.support.AbstractApplicationContext
public <T> T getBean(Class<T> requiredType) throws BeansException {
return getBeanFactory().getBean(requiredType);
}
-- org.springframework.beans.factory.support.DefaultListableBeanFactory
public <T> T getBean(Class<T> requiredType) throws BeansException {
return getBean(requiredType, (Object[]) null);
}
public <T> T getBean(Class<T> requiredType, Object... args) throws BeansException {
String[] beanNames = getBeanNamesForType(requiredType);
if (beanNames.length == 1) {
return getBean(beanNames[0], requiredType, args);
}
}
-- org.springframework.beans.factory.support.AbstractBeanFactory.getBean
public <T> T getBean(String name, Class<T> requiredType, Object[] args) throws BeansException {
return doGetBean(name, requiredType, args, false);
}
-------------------- 根据名字获取Bean最终调用的也是doGetBean方法
-- org.springframework.context.support.AbstractApplicationContext
public Object getBean(String name) throws BeansException {
return getBeanFactory().getBean(name);
}
-- org.springframework.beans.factory.support.AbstractBeanFactory
public Object getBean(String name) throws BeansException {
return doGetBean(name, null, null, false);
}
doGetBean方法中很多地方都会调用getObjectForBeanInstance来获取最终需要的bean。该方法是spring为实现FactoryBean而编写的,其内部判断了是否需要利用工厂模式来创建出目标bean,详细伪代码如下:
protected Object getObjectForBeanInstance(Object beanInstance, String name, String beanName, RootBeanDefinition mbd) {
-- 如果对象不是一个FactoryBean或者这里就是要取FactoryBean,则直接返回
if (!(beanInstance instanceof FactoryBean) || BeanFactoryUtils.isFactoryDereference(name)) {
return beanInstance;
}
-- 如果对象是一个FactoryBean且这里要获取对应的Bean,则尝试从factoryBean已创建的对象缓存中获取
Object object = null;
if (mbd == null) {
object = getCachedObjectForFactoryBean(beanName);
}
-- 缓存中没有则用Factory去创建出Bean
if (object == null) {
FactoryBean<?> factory = (FactoryBean<?>) beanInstance;
if (mbd == null && containsBeanDefinition(beanName)) {
mbd = getMergedLocalBeanDefinition(beanName);
}
boolean synthetic = (mbd != null && mbd.isSynthetic());
object = getObjectFromFactoryBean(factory, beanName, !synthetic);
}
return object;
}
-- org.springframework.beans.factory.support.FactoryBeanRegistrySupport
protected Object getObjectFromFactoryBean(FactoryBean<?> factory, String beanName, boolean shouldPostProcess) {
Object object = doGetObjectFromFactoryBean(factory, beanName);
object = postProcessObjectFromFactoryBean(object, beanName);
this.factoryBeanObjectCache.put(beanName, (object != null ? object : NULL_OBJECT));
return (object != NULL_OBJECT ? object : null);
}
-- doGetObjectFromFactoryBean中关键代码
object = factory.getObject();
return object;
如果factory缓存中没有需要的Bean时,不管是单例Bean、模板Bean,最终都会调用createBean方法来创建一个Bean,并调用getObjectForBeanInstance方法确定目标bean。createBean内部会调用doCreateBean方法进行对象的创建、初始化等工作,详细伪代码如下:
-- doGetBean
Object bean = createBean(beanName, mbd, args);
bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
-- org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory
protected Object createBean(final String beanName, final RootBeanDefinition mbd, final Object[] args) {
resolveBeanClass(mbd, beanName);
mbd.prepareMethodOverrides();
Object bean = resolveBeforeInstantiation(beanName, mbd);
if (bean != null) {
return bean;
}
Object beanInstance = doCreateBean(beanName, mbd, args);
return beanInstance;
}
-- org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean
protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final Object[] args) {
// 创建目标对象,包装成BeanWrapper
BeanWrapper instanceWrapper = createBeanInstance(beanName, mbd, args);
// 执行MergedBeanDefinitionPostProcessor接口
applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);
//将单例添加到Bean工厂的缓存中,解决循环引用问题
...
// 成员变量初始化
populateBean(beanName, mbd, instanceWrapper);
Object exposedObject = initializeBean(beanName, bean, mbd);
//实例化它依赖的Bean
...
//如果这个Bean是可销毁的Bean,则注册到factory中。
registerDisposableBeanIfNecessary(beanName, bean, mbd);
return exposedObject;
}
populateBean和initializeBean完成了Bean的成员变量初始化工作。其中,populateBean方法在属性设置之前调用了InstantiationAwareBeanPostProcessor,允许实现自定义方式的属性注入。之后把依赖的非简单类型取出依赖注入(有set方法的这种)。再把所有属性在类型转换器走一次,设置到Bean中(applyPropertyValues)。
protected void populateBean(String beanName, RootBeanDefinition mbd, BeanWrapper bw) {
PropertyValues pvs = mbd.getPropertyValues();
//调用InstantiationAwareBeanPostProcessor的postProcessAfterInstantiation方法,
ibp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)
if (...) { //允许InstantiationAwareBeanPostProcessor终止初始化流程
return;
}
//根据类型或者名字调用setXXX方法自动注入
autowireByXXX(beanName, mbd, bw, newPvs);
//成员被自动注入后,调用InstantiationAwareBeanPostProcessor的postProcessPropertyValues方法
pvs = ibp.postProcessPropertyValues(pvs, filteredPds, bw.getWrappedInstance(), beanName);
if (pvs == null) {
return;
}
//解析所有运行时的引用,应用所有的属性值(包含类型转换)。
applyPropertyValues(beanName, mbd, bw, pvs);
}
initializeBean调用了些Aware方法:
- BeanNameAware
- BeanClassLoaderAware
- BeanFactoryAware
调用BeanPostProcessor的postProcessBeforeInitialization方法(例如ApplicationContextAware)。如果Bean实现了InitializingBean,则调用它的afterPropertiesSet方法。调用Bean设置的initMethod方法,调用BeanPostProcessor的postProcessAfterInitialization方法。详细的伪代码如下:
protected Object initializeBean(final String beanName, final Object bean, RootBeanDefinition mbd) {
invokeAwareMethods(beanName, bean);
Object wrappedBean = bean;
wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
//包含InitializingBean的方法和自定义的init方法
invokeInitMethods(beanName, wrappedBean, mbd);
wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
return wrappedBean;
}
四、总结
spring实例化Bean过程,提供了许多扩展点。其Factory Bean模式也是通过getBean方法内部做了特殊处理才实现的。在Bean被实例化之前,会调用MergedBeanDefinitionPostProcessor进行预处理,给予了我们对对象进行代理的机会,使其不去创建具体的目标类型对象。在配置文件加载前、加载后,spring都提供了可供我们添加逻辑的接口,来实现自己的增强功能。
对ApplicationContext初始化流程不熟悉的话,可以参考这篇文章:spring扩展之application context初始化流程