在创建完事件传播器并将所有ApplicationListener注册到时间传播器中后,就开始创建剩余的单实例bean了。
剩下会通过调用beanFactory的preInstantiateSingletons方法进行创建
protected void finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory) {
......
//创建剩余的单实例bean
beanFactory.preInstantiateSingletons();
}
进入preInstantiateSingletons方法
- 首先获取到说有的bean定义的名称
- 如果这个名称对应的bean不是抽象的,并且是单实例的,并且不是懒加载的
- 如果是FactoryBean走创建工厂的逻辑
- 如果不是FactoryBean,则调用getBean(beanName)来创建这个bean
public void preInstantiateSingletons() throws BeansException {
......
List<String> 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()) {
//不是抽象的 && 是单实例的 && 不是懒加载的
if (isFactoryBean(beanName)) {
//如果是工厂bean
......
}
else {
//普通的bean
getBean(beanName);
}
}
}
......
}
getBean(beanName)方法直接调用了doGetBean(name, null, null, false)方法
public Object getBean(String name) throws BeansException {
return doGetBean(name, null, null, false);
}
查看doGetBean方法的逻辑
- 首先通过getSingleton(beanName)尝试获取一个bean
- 从单实例bean集合中获取已经生成好的bean
- 如果当前beanName没有已经创建好的bean,则尝试从二级缓存中获取
- 这个二级缓存用来存放提前暴露的bean,解决了循环依赖的问题
- 如果二级缓存中依然没有,则尝试获取当前beanName的工厂
- 如果获取到了bean工厂,则通过调用工厂的getObject()方法来获取一个提前暴露的bean
- 将这个提前暴露的bean添加到二级缓存中
- 将当前bean工厂删除
- 如果getSingleton(beanName)没有获取到bean对象,则通过createBean(beanName, mbd, args)方法来获取bean
protected <T> T doGetBean(final String name, @Nullable final Class<T> requiredType,
@Nullable final Object[] args, boolean typeCheckOnly) throws BeansException {
......
//尝试直接获取对象
Object sharedInstance = getSingleton(beanName);
......
// 创建单实例bean
if (mbd.isSingleton()) {
sharedInstance = getSingleton(beanName, () -> {
try {
//创建单实例bean
return createBean(beanName, mbd, args);
}
catch (BeansException ex) {
......
}
});
bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
}
......
return (T) bean;
}
getSingleton(beanName)方法逻辑
- 从单实例bean集合中获取已经生成好的bean
- 如果当前beanName没有已经创建好的bean,则尝试从二级缓存中获取
- 这个二级缓存用来存放提前暴露的bean,解决了循环依赖的问题
- 如果二级缓存中依然没有,则尝试获取当前beanName的工厂
- 如果获取到了bean工厂,则通过调用工厂的getObject()方法来获取一个提前暴露的bean
- 将这个提前暴露的bean添加到二级缓存中
- 将当前bean工厂删除
protected Object getSingleton(String beanName, boolean allowEarlyReference) {
//从单实例bean集合中获取已经生成好的bean
Object singletonObject = this.singletonObjects.get(beanName);
if (singletonObject == null && isSingletonCurrentlyInCreation(beanName)) {
//如果当前beanName没有已经创建好的bean,则尝试从二级缓存中获取
synchronized (this.singletonObjects) {
singletonObject = this.earlySingletonObjects.get(beanName);
if (singletonObject == null && allowEarlyReference) {
//如果二级缓存中依然没有,则尝试获取当前beanName的工厂
//在spring创建出bean对象之后,依赖注入之前,会向singletonFactories中添加一个工厂,用来提前暴露bean的包装对象,来解决循环依赖问题
ObjectFactory<?> singletonFactory = this.singletonFactories.get(beanName);
if (singletonFactory != null) {
//如果可以获取到工厂,则利用工厂获取bean,并添加到二级缓存中,并且将工厂从集合中移除
singletonObject = singletonFactory.getObject();
this.earlySingletonObjects.put(beanName, singletonObject);
this.singletonFactories.remove(beanName);
}
}
}
}
return singletonObject;
}
createBean(beanName, mbd, args)的逻辑
- 先执行resolveBeforeInstantiation(beanName, mbdToUse)方法,如果返回值不为空,则返回
- 如果第一步没有返回bean,则通过doCreateBean(beanName, mbdToUse, args),获取bean
protected Object createBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)
throws BeanCreationException {
......
try {
//先执行InstantiationAwareBeanPostProcessor的postProcessBeforeInstantiation方法,获取bean对象
//如果获取到了bean对象,则调用BeanPostProcessor的postProcessAfterInitialization方法
Object bean = resolveBeforeInstantiation(beanName, mbdToUse);
if (bean != null) {
return bean;
}
}
......
try {
//创建单实例bean
Object beanInstance = doCreateBean(beanName, mbdToUse, args);
if (logger.isTraceEnabled()) {
logger.trace("Finished creating instance of bean '" + beanName + "'");
}
return beanInstance;
}
......
}
resolveBeforeInstantiation(beanName, mbdToUse)方法的逻辑
- 遍历所有的BeanPostProcessor
- 如果这个BeanPostProcessor是InstantiationAwareBeanPostProcessor类型的
- 调用postProcessBeforeInstantiation方法,如果返回值不为空,则结束当前循环
- 如果这个BeanPostProcessor是InstantiationAwareBeanPostProcessor类型的
- 如果第一步循环中postProcessBeforeInstantiation有非空返回值,则遍历所有的BeanPostProcessor并调用postProcessAfterInitialization方法
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) {
//执行InstantiationAwareBeanPostProcessor的postProcessBeforeInstantiation方法,来获取一个bean
bean = applyBeanPostProcessorsBeforeInstantiation(targetType, beanName);
if (bean != null) {
//如果获取到了,则调用BeanPostProcessor的postProcessAfterInitialization方法
bean = applyBeanPostProcessorsAfterInitialization(bean, beanName);
}
}
}
mbd.beforeInstantiationResolved = (bean != null);
}
return bean;
}
protected Object applyBeanPostProcessorsBeforeInstantiation(Class<?> beanClass, String beanName) {
for (BeanPostProcessor bp : getBeanPostProcessors()) {
//遍历所有的BeanPostProcessor
if (bp instanceof InstantiationAwareBeanPostProcessor) {
//如果是InstantiationAwareBeanPostProcessor,则执行postProcessBeforeInstantiation方法
InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
Object result = ibp.postProcessBeforeInstantiation(beanClass, beanName);
//如果返回值非空,则直接返回结果
if (result != null) {
return result;
}
}
}
return null;
}
public Object applyBeanPostProcessorsAfterInitialization(Object existingBean, String beanName)
throws BeansException {
Object result = existingBean;
//调用所有BeanPostProcessor的postProcessAfterInitialization方法
for (BeanPostProcessor processor : getBeanPostProcessors()) {
Object current = processor.postProcessAfterInitialization(result, beanName);
if (current == null) {
return result;
}
result = current;
}
return result;
}
doCreateBean(beanName, mbdToUse, args)的逻辑
- 首先通过反射创建出bean对象
- 调用容器中所有MergedBeanDefinitionPostProcessor类型的BeanPostProcessor的postProcessMergedBeanDefinition()方法
- 创建一个单例工厂
- 添加一个ObjectFactory到singletonFactories集合中,在上面的getSingleton(beanName)中会使用
- 将当前的beanName从earlySingletonObjects集合中删除
- getEarlyBeanReference方法的作用:获取到所有的SmartInstantiationAwareBeanPostProcessor
- 然后执行这些SmartInstantiationAwareBeanPostProcessor的getEarlyBeanReference方法
- 调用populateBean(beanName, mbd, instanceWrapper)对属性进行注入
- 首先先调用了所有InstantiationAwareBeanPostProcessor的postProcessAfterInstantiation方法
- 然后调用InstantiationAwareBeanPostProcessor的postProcessPropertyValues方法
- 然后再对当前bean进行依赖注入
- 调用initializeBean(beanName, exposedObject, mbd)执行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) {
instanceWrapper = createBeanInstance(beanName, mbd, args);
}
//利用反射创建出bean对象
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.
synchronized (mbd.postProcessingLock) {
if (!mbd.postProcessed) {
try {
//调用容器中所有MergedBeanDefinitionPostProcessor类型的BeanPostProcessor的postProcessMergedBeanDefinition()方法
applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);
}
catch (Throwable ex) {
throw new BeanCreationException(mbd.getResourceDescription(), beanName,
"Post-processing of merged bean definition failed", ex);
}
mbd.postProcessed = true;
}
}
//防止循环依赖的处理
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");
}
//添加一个ObjectFactory到singletonFactories集合中,在上面的getSingleton(beanName)中会使用
//将当前的beanName从earlySingletonObjects集合中删除
//getEarlyBeanReference方法的作用:获取到所有的SmartInstantiationAwareBeanPostProcessor
//然后执行这些SmartInstantiationAwareBeanPostProcessor的getEarlyBeanReference方法
addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean));
}
// Initialize the bean instance.
Object exposedObject = bean;
try {
//DI
//首先先调用了所有InstantiationAwareBeanPostProcessor的postProcessAfterInstantiation方法
//然后调用InstantiationAwareBeanPostProcessor的postProcessPropertyValues方法
//然后再对当前bean进行依赖注入
populateBean(beanName, mbd, instanceWrapper);
//初始化bean
exposedObject = initializeBean(beanName, exposedObject, mbd);
}
......
// Register bean as disposable.
try {
registerDisposableBeanIfNecessary(beanName, bean, mbd);
}
catch (BeanDefinitionValidationException ex) {
throw new BeanCreationException(
mbd.getResourceDescription(), beanName, "Invalid destruction signature", ex);
}
return exposedObject;
}
接下来看下addSingletonFactory方法的逻辑
- 调用代码addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean));
- 这里有两个方法第一个是addSingletonFactory,第二个是getEarlyBeanReference
- addSingletonFactory
- 如果当前bean在单实例集合中不存在
- 将singletonFactory添加到三级缓存singletonFactories中
- 将二级缓存中的beanName删除
- getEarlyBeanReference,这个方法就是singletonFactory的getObject的实现
- 遍历所有的SmartInstantiationAwareBeanPostProcessor类型的BeanPostProcessor
- 执行SmartInstantiationAwareBeanPostProcessor的getEarlyBeanReference方法
- 在AOP中,会想容器中添加一个AnnotationAwareAspectJAutoProxyCreator类型的SmartInstantiationAwareBeanPostProcessor
- 而这个AnnotationAwareAspectJAutoProxyCreator中有两个方法会对当前的bean做AOP代理
- getEarlyBeanReference()这个是SmartInstantiationAwareBeanPostProcessor接口的方法
- postProcessAfterInitialization()这个是BeanPostProcessor接口的方法
protected void addSingletonFactory(String beanName, ObjectFactory<?> singletonFactory) {
Assert.notNull(singletonFactory, "Singleton factory must not be null");
synchronized (this.singletonObjects) {
//如果当前bean在单实例集合中不存在
if (!this.singletonObjects.containsKey(beanName)) {
//将singletonFactory添加到三级缓存singletonFactories中
this.singletonFactories.put(beanName, singletonFactory);
//将二级缓存中的beanName删除
this.earlySingletonObjects.remove(beanName);
this.registeredSingletons.add(beanName);
}
}
}
protected Object getEarlyBeanReference(String beanName, RootBeanDefinition mbd, Object bean) {
Object exposedObject = bean;
if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
for (BeanPostProcessor bp : getBeanPostProcessors()) {
if (bp instanceof SmartInstantiationAwareBeanPostProcessor) {
//遍历所有的SmartInstantiationAwareBeanPostProcessor类型的BeanPostProcessor
SmartInstantiationAwareBeanPostProcessor ibp = (SmartInstantiationAwareBeanPostProcessor) bp;
//执行SmartInstantiationAwareBeanPostProcessor的getEarlyBeanReference方法
//在AOP中,会想容器中添加一个AnnotationAwareAspectJAutoProxyCreator类型的SmartInstantiationAwareBeanPostProcessor
//而这个AnnotationAwareAspectJAutoProxyCreator中有两个方法会对当前的bean做AOP代理
//第一个getEarlyBeanReference,第二个postProcessAfterInitialization
exposedObject = ibp.getEarlyBeanReference(exposedObject, beanName);
}
}
}
return exposedObject;
}
继续看bean的属性注入方法
- populateBean(beanName, mbd, instanceWrapper);
- 遍历执行InstantiationAwareBeanPostProcessor的postProcessAfterInstantiation方法
- 执行InstantiationAwareBeanPostProcessor的postProcessPropertyValues方法
- 对bean进行属性注入
protected void populateBean(String beanName, RootBeanDefinition mbd, @Nullable BeanWrapper bw) {
......
boolean continueWithPropertyPopulation = true;
if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
for (BeanPostProcessor bp : getBeanPostProcessors()) {
if (bp instanceof InstantiationAwareBeanPostProcessor) {
//遍历执行InstantiationAwareBeanPostProcessor的postProcessAfterInstantiation方法
InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
if (!ibp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) {
continueWithPropertyPopulation = false;
break;
}
}
}
}
if (!continueWithPropertyPopulation) {
return;
}
......
PropertyDescriptor[] filteredPds = null;
if (hasInstAwareBpps) {
if (pvs == null) {
pvs = mbd.getPropertyValues();
}
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);
}
//执行InstantiationAwareBeanPostProcessor的postProcessPropertyValues方法
pvsToUse = ibp.postProcessPropertyValues(pvs, filteredPds, bw.getWrappedInstance(), beanName);
if (pvsToUse == null) {
return;
}
}
pvs = pvsToUse;
}
}
}
......
if (pvs != null) {
//对bean进行属性注入
applyPropertyValues(beanName, mbd, bw, pvs);
}
}
最后再看bean的初始化
- initializeBean(beanName, exposedObject, mbd)
- invokeAwareMethods(beanName, bean);
- 如果当前bean实现了BeanNameAware接口,则执行setBeanName()方法
- 如果当前bean实现了BeanClassLoaderAware接口,则执行BeanClassLoaderAware()方法
- 如果当前bean实现了BeanFactoryAware接口,则执行setBeanFactory()方法
- applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
- 执行BeanPostProcessor的postProcessBeforeInitialization()方法
- invokeInitMethods(beanName, wrappedBean, mbd);
- 如果当前bean实现了InitializingBean接口则执行afterPropertiesSet()方法
- 再执行自定义的初始化方法
- applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
- 执行BeanPostProcessor的postProcessAfterInitialization()方法
- spring的AOP在这里,通过postProcessAfterInitialization()实现对bean的动态代理,并返回了代理后的对象
- 执行BeanPostProcessor的postProcessAfterInitialization()方法
- invokeAwareMethods(beanName, bean);
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接口,则执行setBeanName()方法
//如果当前bean实现了BeanClassLoaderAware接口,则执行BeanClassLoaderAware()方法
//如果当前bean实现了BeanFactoryAware接口,则执行setBeanFactory()方法
invokeAwareMethods(beanName, bean);
}
Object wrappedBean = bean;
if (mbd == null || !mbd.isSynthetic()) {
//执行BeanPostProcessor的postProcessBeforeInitialization()方法
wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
}
try {
//如果当前bean实现了InitializingBean接口则执行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的postProcessAfterInitialization()方法
wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
}
return wrappedBean;
}
private void invokeAwareMethods(final String beanName, final Object bean) {
if (bean instanceof Aware) {
if (bean instanceof BeanNameAware) {
((BeanNameAware) bean).setBeanName(beanName);
}
if (bean instanceof BeanClassLoaderAware) {
ClassLoader bcl = getBeanClassLoader();
if (bcl != null) {
((BeanClassLoaderAware) bean).setBeanClassLoader(bcl);
}
}
if (bean instanceof BeanFactoryAware) {
((BeanFactoryAware) bean).setBeanFactory(AbstractAutowireCapableBeanFactory.this);
}
}
}
public Object applyBeanPostProcessorsBeforeInitialization(Object existingBean, String beanName)
throws BeansException {
Object result = existingBean;
for (BeanPostProcessor processor : getBeanPostProcessors()) {
Object current = processor.postProcessBeforeInitialization(result, beanName);
if (current == null) {
return result;
}
result = current;
}
return result;
}
protected void invokeInitMethods(String beanName, final Object bean, @Nullable RootBeanDefinition mbd)
throws Throwable {
boolean isInitializingBean = (bean instanceof InitializingBean);
if (isInitializingBean && (mbd == null || !mbd.isExternallyManagedInitMethod("afterPropertiesSet"))) {
......
//如果是InitializingBean接口
//调用afterPropertiesSet方法
((InitializingBean) bean).afterPropertiesSet();
}
if (mbd != null && bean.getClass() != NullBean.class) {
String initMethodName = mbd.getInitMethodName();
//如果有自定义的初始化方法
if (StringUtils.hasLength(initMethodName) &&
!(isInitializingBean && "afterPropertiesSet".equals(initMethodName)) &&
!mbd.isExternallyManagedInitMethod(initMethodName)) {
//执行初始化方法
invokeCustomInitMethod(beanName, bean, mbd);
}
}
}
public Object applyBeanPostProcessorsAfterInitialization(Object existingBean, String beanName)
throws BeansException {
Object result = existingBean;
//调用所有BeanPostProcessor的postProcessAfterInitialization方法
for (BeanPostProcessor processor : getBeanPostProcessors()) {
Object current = processor.postProcessAfterInitialization(result, beanName);
if (current == null) {
return result;
}
result = current;
}
return result;
}