在Spring容器创建,并调用refresh()方法时,会刷新容器,并实现IOC过程创建bean。refresh方法中实现IOC的调用的主要方法方法有:
- registerBeanPostProcessors(beanFactory); 注册BeanPostProcessor,用于拦截bean的创建过程。
- finishBeanFactoryInitialization(beanFactory);初始化所有剩下的单实例bean,也就是IOC创建单例bean的过程。
registerBeanPostProcessors(beanFactory);
public static void registerBeanPostProcessors(
ConfigurableListableBeanFactory beanFactory, AbstractApplicationContext applicationContext) {
String[] postProcessorNames = beanFactory.getBeanNamesForType(BeanPostProcessor.class, true, false);
// 注册BeanPostProcessorChecker,bean不能被所有BeanPostProcessor处理时,记录一条消息。
int beanProcessorTargetCount = beanFactory.getBeanPostProcessorCount() + 1 + postProcessorNames.length;
beanFactory.addBeanPostProcessor(new BeanPostProcessorChecker(beanFactory, beanProcessorTargetCount));
//根据优先级将BeanPostProcessors分组
List<BeanPostProcessor> priorityOrderedPostProcessors = new ArrayList<BeanPostProcessor>();
List<BeanPostProcessor> internalPostProcessors = new ArrayList<BeanPostProcessor>();
List<String> orderedPostProcessorNames = new ArrayList<String>();
List<String> nonOrderedPostProcessorNames = new ArrayList<String>();
for (String ppName : postProcessorNames) {
if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
priorityOrderedPostProcessors.add(pp);
if (pp instanceof MergedBeanDefinitionPostProcessor) {
internalPostProcessors.add(pp);
}
}
else if (beanFactory.isTypeMatch(ppName, Ordered.class)) {
orderedPostProcessorNames.add(ppName);
}
else {
nonOrderedPostProcessorNames.add(ppName);
}
}
//注册实现PriorityOrdered接口的 BeanPostProcessors
sortPostProcessors(priorityOrderedPostProcessors, beanFactory);
registerBeanPostProcessors(beanFactory, priorityOrderedPostProcessors);
// 注册实现Ordered接口的BeanPostProcessors
List<BeanPostProcessor> orderedPostProcessors = new ArrayList<BeanPostProcessor>();
for (String ppName : orderedPostProcessorNames) {
BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
orderedPostProcessors.add(pp);
if (pp instanceof MergedBeanDefinitionPostProcessor) {
internalPostProcessors.add(pp);
}
}
sortPostProcessors(orderedPostProcessors, beanFactory);
registerBeanPostProcessors(beanFactory, orderedPostProcessors);
// 注册没有实现优先级接口的BeanPostProcessors.
List<BeanPostProcessor> nonOrderedPostProcessors = new ArrayList<BeanPostProcessor>();
for (String ppName : nonOrderedPostProcessorNames) {
BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
nonOrderedPostProcessors.add(pp);
if (pp instanceof MergedBeanDefinitionPostProcessor) {
internalPostProcessors.add(pp);
}
}
registerBeanPostProcessors(beanFactory, nonOrderedPostProcessors);
// 最后注册internal BeanPostProcessors,也就是MergedBeanDefinitionPostProcessor.
sortPostProcessors(internalPostProcessors, beanFactory);
registerBeanPostProcessors(beanFactory, internalPostProcessors);
// 将检测内部bean的后处理器重新注册为applicationlistener,将其移动到处理器链的末尾(用于获取代理等)。
beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(applicationContext));
}
从上面的代码中可以看到registerBeanPostProcessors的工作是:
- 1)、获取所有的 BeanPostProcessor;后置处理器都默认可以通过PriorityOrdered、Ordered接口来执行优先级
- 2)、先注册PriorityOrdered优先级接口的BeanPostProcessor; 把每一个BeanPostProcessor;添加到BeanFactory中
beanFactory.addBeanPostProcessor(postProcessor); - 3)、再注册Ordered接口的
- 4)、最后注册没有实现任何优先级接口的
- 5)、最终注册MergedBeanDefinitionPostProcessor;
- 6)、注册一个ApplicationListenerDetector;来在Bean创建完成后检查是否是ApplicationListener,如果是 applicationContext.addApplicationListener((ApplicationListener<?>) bean);
finishBeanFactoryInitialization(beanFactory);初始化所有剩下的单实例bean:
初始化bean实例的的流程:
1、beanFactory.preInstantiateSingletons();初始化后剩下的单实例bean
1.1、获取容器中的所有Bean,依次进行初始化和创建对象
1.2、获取Bean的定义信息;RootBeanDefinition
1.3、Bean不是抽象的,是单实例的,是懒加载;
1.3.1、判断是否是FactoryBean;是否是实现FactoryBean接口的Bean;
1.3.2、不是工厂Bean。利用getBean(beanName);创建对象
1.3.2.1、doGetBean(name, null, null, false);
1.3.2.2、先获取缓存中保存的单实例Bean。如果能获取到说明这个Bean之前被创建过(所有创建过的单实例Bean都会被缓存起来)
从private final Map<String, Object> singletonObjects = new ConcurrentHashMap<String, Object>(256);获取的
1.3.2.3、缓存中获取不到,开始Bean的创建对象流程;
1.3.2. 4、标记当前bean已经被创建
1.3.2.5、获取Bean的定义信息;
1.3.2.6、【获取当前Bean依赖的其他Bean;如果有按照getBean()把依赖的Bean先创建出来;】
1.3.2.7、启动单实例Bean的创建流程;
1)、createBean(beanName, mbd, args);
2)、Object bean = resolveBeforeInstantiation(beanName, mbdToUse);让BeanPostProcessor先拦截返回代理对象;
【InstantiationAwareBeanPostProcessor】:提前执行;
先触发:postProcessBeforeInstantiation();
如果有返回值:触发postProcessAfterInitialization();
3)、如果前面的InstantiationAwareBeanPostProcessor没有返回代理对象;调用4)
4)、Object beanInstance = doCreateBean(beanName, mbdToUse, args);创建Bean
(1)、【创建Bean实例】;createBeanInstance(beanName, mbd, args);
利用工厂方法或者对象的构造器创建出Bean实例;
(2)、applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);
调用MergedBeanDefinitionPostProcessor的postProcessMergedBeanDefinition(mbd, beanType, beanName);
(3)、【Bean属性赋值】populateBean(beanName, mbd, instanceWrapper);
赋值之前:
1)、拿到InstantiationAwareBeanPostProcessor后置处理器; postProcessAfterInstantiation();
2)、拿到InstantiationAwareBeanPostProcessor后置处理器; postProcessPropertyValues();
=====赋值之前:===
3)、应用Bean属性的值;为属性利用setter方法等进行赋值; applyPropertyValues(beanName, mbd, bw, pvs);
(4)、【Bean初始化】initializeBean(beanName, exposedObject, mbd);
1)、【执行Aware接口方法】invokeAwareMethods(beanName, bean);执行xxxAware接口的方法
BeanNameAware\BeanClassLoaderAware\BeanFactoryAware
2)、【执行后置处理器初始化之前】applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
BeanPostProcessor.postProcessBeforeInitialization();
3)、【执行初始化方法】invokeInitMethods(beanName, wrappedBean, mbd);
1)、是否是InitializingBean接口的实现;执行接口规定的初始化;
2)、是否自定义初始化方法;
4)、【执行后置处理器初始化之后】applyBeanPostProcessorsAfterInitialization
BeanPostProcessor.postProcessAfterInitialization();
(5)、注册Bean的销毁方法;
5)、将创建的Bean添加到缓存中singletonObjects;
ioc容器就是这些Map;很多的Map里面保存了单实例Bean、环境信息等; 所有Bean都利用getBean创建完成以后;
1.3.3检查所有的Bean是否是SmartInitializingSingleton接口的;如果是;就执行afterSingletonsInstantiated();
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));
}
// 如果之前没有注册bean后处理器,则注册一个默认的值解析器:主要用于在注释属性值中解析。
if (!beanFactory.hasEmbeddedValueResolver()) {
beanFactory.addEmbeddedValueResolver(new StringValueResolver() {
@Override
public String resolveStringValue(String strVal) {
return getEnvironment().resolvePlaceholders(strVal);
}
});
}
// 初始化LoadTimeWeaverAware bean,以便尽早注册它们的转换器
String[] weaverAwareNames = beanFactory.getBeanNamesForType(LoadTimeWeaverAware.class, false, false);
for (String weaverAwareName : weaverAwareNames) {
getBean(weaverAwareName);
}
//停止使用临时类加载器进行类型匹配
beanFactory.setTempClassLoader(null);
//缓存所有bean定义元数据
beanFactory.freezeConfiguration();
// 实例化所有剩余的(非惰性初始化)单例。
beanFactory.preInstantiateSingletons();
}
方法中只有beanFactory.preInstantiateSingletons();用来创建bean实例,上面的各种操作都是一些JVM信息和bean创建前的准备工作。
beanFactory.preInstantiateSingletons():
@Override
public void preInstantiateSingletons() throws BeansException {
if (this.logger.isDebugEnabled()) {
this.logger.debug("Pre-instantiating singletons in " + this);
}
//获取容器中所有bean的定义信息。迭代一个副本以允许init方法,而init方法反过来注册新的bean定义
List<String> beanNames = new ArrayList<String>(this.beanDefinitionNames);
//触发所有非懒加载单例bean的初始化…
for (String beanName : beanNames) {
RootBeanDefinition bd = getMergedLocalBeanDefinition(beanName);
if (!bd.isAbstract() && bd.isSingleton() && !bd.isLazyInit()) {//非抽象类、单例、非懒加载
if (isFactoryBean(beanName)) { //如果是工厂bean
final FactoryBean<?> factory = (FactoryBean<?>) getBean(FACTORY_BEAN_PREFIX + beanName);
boolean isEagerInit;
if (System.getSecurityManager() != null && factory instanceof SmartFactoryBean) {
isEagerInit = AccessController.doPrivileged(new PrivilegedAction<Boolean>() {
@Override
public Boolean run() {
return ((SmartFactoryBean<?>) factory).isEagerInit();
}
}, getAccessControlContext());
} else {
isEagerInit = (factory instanceof SmartFactoryBean &&
((SmartFactoryBean<?>) factory).isEagerInit());
}
if (isEagerInit) {
getBean(beanName);
}
} else { //不是工厂bean
getBean(beanName);
}
}
}
//为所有适用的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(new PrivilegedAction<Object>() {
@Override
public Object run() {
smartSingleton.afterSingletonsInstantiated();
return null;
}
}, getAccessControlContext());
}
else {
smartSingleton.afterSingletonsInstantiated();
}
}
}
}
beanFactory.preInstantiateSingletons();初始化后剩下的单实例bean
1)、获取容器中的所有Bean,依次进行初始化和创建对象
2)、获取Bean的定义信息;RootBeanDefinition
3)、Bean不是抽象的,是单实例的,非懒加载;
1)、判断是否是FactoryBean;是否是实现FactoryBean接口的Bean;
2)、不是工厂Bean。利用getBean(beanName);创建对象
无论目标bean是否工厂bean,都会调用getBean方法创建bean实例,另外还发现getBean方法的返回值,并没有被接受,那么创建的bean存放到了哪里呢,我们又如何从容器中获取bean的呢?下面就来看看getBean是如何创建和存储bean的。
getBean():
public Object getBean(String name) throws BeansException {
return doGetBean(name, null, null, false); //直接调用doGetBean方法
}
doGetBean(name, null, null, false):
protected <T> T doGetBean(
final String name, final Class<T> requiredType, final Object[] args, boolean typeCheckOnly)
throws BeansException {
final String beanName = transformedBeanName(name);
Object bean;
//先获取缓存中的单例bean(所有创建过得bean都会被缓存)
Object sharedInstance = getSingleton(beanName);
if (sharedInstance != null && args == null) {//从缓存中获取
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 + "'");
}
}
bean = getObjectForBeanInstance(sharedInstance, name, beanName, null);
}else { //缓存中没有获取到目标bean
if (isPrototypeCurrentlyInCreation(beanName)) {
throw new BeanCurrentlyInCreationException(beanName);
}
// 检查这个工厂中是否存在bean定义。(开始创建bean)
BeanFactory parentBeanFactory = getParentBeanFactory();
if (parentBeanFactory != null && !containsBeanDefinition(beanName)) {
// 未找到->检查父节点。
String nameToLookup = originalBeanName(name);
if (args != null) {
// 使用显式args委托给父对象。
return (T) parentBeanFactory.getBean(nameToLookup, args);
}
else {
// 没有args ->委托给标准getBean方法。
return parentBeanFactory.getBean(nameToLookup, requiredType);
}
}
if (!typeCheckOnly) { //标记当前bean已经被创建
markBeanAsCreated(beanName);
}
try {
//获取bean的定义信息
final RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
checkMergedBeanDefinition(mbd, beanName, args);
// 获取当前bean依赖的其他bean
String[] dependsOn = mbd.getDependsOn();
if (dependsOn != null) {
for (String dep : dependsOn) {
if (isDependent(beanName, dep)) {
throw new BeanCreationException(mbd.getResourceDescription(), beanName,
"Circular depends-on relationship between '" + beanName + "' and '" + dep + "'");
}
registerDependentBean(dep, beanName);
getBean(dep); //调用getBean。注册依赖的bean
}
}
//创建bean实例:
if (mbd.isSingleton()) {
sharedInstance = getSingleton(beanName, new ObjectFactory<Object>() {
@Override
public Object getObject() throws BeansException {
try {
return createBean(beanName, mbd, args);
}
catch (BeansException ex) {
destroySingleton(beanName);
throw ex;
}
}
});
bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
}else if (mbd.isPrototype()) {
//创建一个新实例。
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, new ObjectFactory<Object>() {
@Override
public Object getObject() throws BeansException {
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;
}
}
// 检查所需类型是否与实际bean实例的类型匹配
if (requiredType != null && bean != null && !requiredType.isInstance(bean)) {
try {
return getTypeConverter().convertIfNecessary(bean, requiredType);
}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());
}
}
return (T) bean;
}
doGetBean方法的执行流程:
- 先获取缓存中保存的单实例Bean: getSingleTon()。如果能获取到说明这个Bean之前被创建过(所有创建过的单实例Bean都会被缓存起来)。从private final Map<String, Object> singletonObjects = new ConcurrentHashMap<String, Object>(256);获取的
- 如果缓存中获取不到,开始Bean的创建对象流程;
- 标记当前bean已经被创建: markBeanAsCreated方法
- 获取Bean的定义信息;
- 获取当前Bean依赖的其他Bean;如果有按照getBean()把依赖的Bean先创建出来;
- 启动单实例Bean的创建流程;sharedInstance = getSingleton(beanName, new ObjectFactory<Object>() {......}); 这里的getSingleton方法,调用了createBean方法(AbstractAutowireCapableBeanFactory类中实现)创建bean实例。
下面分别来看看getSingleTon获取缓存中的实例,markBeanAsCreated标记bean已经被创建,createBean创建bean实例,三个方法是如何实现的:
getSingleton():获取缓存中的单例bean
protected Object getSingleton(String beanName, boolean allowEarlyReference) {
//private final Map<String, Object> singletonObjects = new ConcurrentHashMap<String, Object>(256);
Object singletonObject = this.singletonObjects.get(beanName);
if (singletonObject == null && isSingletonCurrentlyInCreation(beanName)) {
synchronized (this.singletonObjects) {
singletonObject = this.earlySingletonObjects.get(beanName);
if (singletonObject == null && allowEarlyReference) {
ObjectFactory<?> singletonFactory = this.singletonFactories.get(beanName);
if (singletonFactory != null) {
singletonObject = singletonFactory.getObject();
this.earlySingletonObjects.put(beanName, singletonObject);
this.singletonFactories.remove(beanName);
}
}
}
}
return (singletonObject != NULL_OBJECT ? singletonObject : null);
}
markBeanAsCreated(String beanName) :标记bean已经被创建
protected void markBeanAsCreated(String beanName) {
//private final Set<String> alreadyCreated = Collections.newSetFromMap(new ConcurrentHashMap<String, Boolean>(256));
if (!this.alreadyCreated.contains(beanName)) {
synchronized (this.mergedBeanDefinitions) {
if (!this.alreadyCreated.contains(beanName)) {
// Let the bean definition get re-merged now that we're actually creating
// the bean... just in case some of its metadata changed in the meantime.
clearMergedBeanDefinition(beanName);
this.alreadyCreated.add(beanName);
}
}
}
}
AbstractAutowireCapableBeanFactory的createBean:
protected Object createBean(String beanName, RootBeanDefinition mbd, Object[] args) throws BeanCreationException {
if (logger.isDebugEnabled()) {
logger.debug("Creating instance of bean '" + beanName + "'");
}
RootBeanDefinition mbdToUse = mbd; //bean的定义信息
//解析bean的类型
Class<?> resolvedClass = resolveBeanClass(mbd, beanName);
if (resolvedClass != null && !mbd.hasBeanClass() && mbd.getBeanClassName() != null) {
mbdToUse = new RootBeanDefinition(mbd);
mbdToUse.setBeanClass(resolvedClass);
}
//准备方法覆盖。
try {
mbdToUse.prepareMethodOverrides();
}catch (BeanDefinitionValidationException ex) {
throw new BeanDefinitionStoreException(mbdToUse.getResourceDescription(),
beanName, "Validation of method overrides failed", ex);
}
try {
//让beanpostprocessor有机会返回代理而不是目标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);
}
Object beanInstance = doCreateBean(beanName, mbdToUse, args);
if (logger.isDebugEnabled()) {
logger.debug("Finished creating instance of bean '" + beanName + "'");
}
return beanInstance;
}
createBean方法是Spring IOC创建实例bean的核心,也就是在这个方法中实现了bean实例的创建、属性赋值、初始化等工作。createBean方法的工作流程:
- 获取bean的定义信息RootBeanDefinition
- 将bean类名解析为类引用(如果需要),并将解析后的类存储在bean定义中。
- 验证并准备为该bean定义的方法覆盖。检查是否存在具有指定名称的方法。
- 创建bean的代理对象,如果能够的话:resolveBeforeInstantiation(beanName, mbdToUse);(Spring AOP的功能)
- 如果没能创建bean的代理对象,则创建bean实例。
SpringIOC容器经过之前一系列的准备工作后,在这里开始创建bean实例实现IOC或者创建bean的代理对象实现AOP。这里我们只讨论IOC创建单例bean的过程,对于创建bean的代理对象实现AOP可以参考另一篇博客:https://blog.csdn.net/zhoushimiao1990/article/details/89853368
下面主要来看一下doCreateBean创建bean实例的过程:
doCreateBean:
protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final Object[] args)
throws BeanCreationException {
//实例化bean
BeanWrapper instanceWrapper = null;
if (mbd.isSingleton()) { //如果bean是单例,先移除缓存中的bean
instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);
}
if (instanceWrapper == null) {
instanceWrapper = createBeanInstance(beanName, mbd, args); //反射创建bean实例
}
final Object bean = (instanceWrapper != null ? instanceWrapper.getWrappedInstance() : null);
Class<?> beanType = (instanceWrapper != null ? instanceWrapper.getWrappedClass() : null);
mbd.resolvedTargetType = beanType;
//允许后处理程序修改合并的bean定义。
synchronized (mbd.postProcessingLock) {
if (!mbd.postProcessed) {
try {
//调用MergedBeanDefinitionPostProcessor后置处理器
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.isDebugEnabled()) {
logger.debug("Eagerly caching bean '" + beanName +
"' to allow for resolving potential circular references");
}
addSingletonFactory(beanName, new ObjectFactory<Object>() {
@Override
public Object getObject() throws BeansException {
return getEarlyBeanReference(beanName, mbd, bean);
}
});
}
//初始化bean实例. 给属性赋值、初始化bean
Object exposedObject = bean;
try {
populateBean(beanName, mbd, instanceWrapper); //bean属性赋值,调用后置处理器
if (exposedObject != null) {
exposedObject = initializeBean(beanName, exposedObject, mbd); //初始化bean
}
}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);
if (earlySingletonReference != null) {
if (exposedObject == bean) {
exposedObject = earlySingletonReference;
}else if (!this.allowRawInjectionDespiteWrapping && hasDependentBean(beanName)) {
String[] dependentBeans = getDependentBeans(beanName);
Set<String> actualDependentBeans = new LinkedHashSet<String>(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.");
}
}
}
}
//注册销毁方法
try {
registerDisposableBeanIfNecessary(beanName, bean, mbd);
} catch (BeanDefinitionValidationException ex) {
throw new BeanCreationException(
mbd.getResourceDescription(), beanName, "Invalid destruction signature", ex);
}
return exposedObject;
}
createBean方法的执行过程:
- 创建Bean实例】;createBeanInstance(beanName, mbd, args);利用工厂方法或者对象的构造器创建出Bean实例;
- applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName); 调用MergedBeanDefinitionPostProcessor后置处理器的postProcessMergedBeanDefinition(mbd, beanType, beanName);
- 缓存创建好的bean实例;
- Bean属性赋值:populateBean(beanName, mbd, instanceWrapper);
- Bean初始化:initializeBean(beanName, exposedObject, mbd);
- 注册Bean的销毁方法
这里主要关注一下bean属性赋值和bean初始化的详细过程以及这期间调用的后置处理器:
populateBean(beanName, mbd, instanceWrapper); //bean属性赋值,调用后置处理器InstantiationAwareBeanPostProcessor
protected void populateBean(String beanName, RootBeanDefinition mbd, BeanWrapper bw) {
PropertyValues pvs = mbd.getPropertyValues();
if (bw == null) {
if (!pvs.isEmpty()) {
throw new BeanCreationException(
mbd.getResourceDescription(), beanName, "Cannot apply property values to null instance");
}
else {
//跳过空实例的属性填充阶段。
return;
}
}
//bean属性赋值之前,调用InstantiationAwareBeanPostProcessors后置处理器,修改bean状态
boolean continueWithPropertyPopulation = true;
if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
for (BeanPostProcessor bp : getBeanPostProcessors()) {
if (bp instanceof InstantiationAwareBeanPostProcessor) {
InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
if (!ibp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) {
continueWithPropertyPopulation = false;
break;
}
}
}
}
if (!continueWithPropertyPopulation) {
return;
}
if (mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_NAME ||
mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_TYPE) {
MutablePropertyValues newPvs = new MutablePropertyValues(pvs);
//根据autowire的名称添加属性值。
if (mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_NAME) {
autowireByName(beanName, mbd, bw, newPvs);
}
//根据autowire的类型添加属性值。
if (mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_TYPE) {
autowireByType(beanName, mbd, bw, newPvs);
}
pvs = newPvs;
}
boolean hasInstAwareBpps = hasInstantiationAwareBeanPostProcessors();
boolean needsDepCheck = (mbd.getDependencyCheck() != RootBeanDefinition.DEPENDENCY_CHECK_NONE);
if (hasInstAwareBpps || needsDepCheck) {
PropertyDescriptor[] filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
if (hasInstAwareBpps) {
for (BeanPostProcessor bp : getBeanPostProcessors()) {
//执行InstantiationAwareBeanPostProcessors后置处理器的方法
if (bp instanceof InstantiationAwareBeanPostProcessor) {
InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
pvs = ibp.postProcessPropertyValues(pvs, filteredPds, bw.getWrappedInstance(), beanName);
if (pvs == null) {
return;
}
}
}
}
if (needsDepCheck) {
checkDependencies(beanName, mbd, filteredPds, pvs);
}
}
applyPropertyValues(beanName, mbd, bw, pvs); //为属性利用setter方法赋值
}
populateBean的工作流程:
- 拿到InstantiationAwareBeanPostProcessor后置处理器;postProcessAfterInstantiation();
- 拿到InstantiationAwareBeanPostProcessor后置处理器; postProcessPropertyValues();
- 应用Bean属性的值;为属性利用setter方法等进行赋值; applyPropertyValues(beanName, mbd, bw, pvs);
从这里可以看出,InstantiationAwareBeanPostProcessor后置处理器的执行时机,实在bean实例化之后,属性赋值之前执行。
initializeBean(beanName, exposedObject, mbd); //初始化bean
protected Object initializeBean(final String beanName, final Object bean, RootBeanDefinition mbd) {
if (System.getSecurityManager() != null) {
AccessController.doPrivileged(new PrivilegedAction<Object>() {
@Override
public Object run() {
invokeAwareMethods(beanName, bean);
return null;
}
}, getAccessControlContext());
}else {
invokeAwareMethods(beanName, bean); //执行Aware接口的方法
}
Object wrappedBean = bean;
if (mbd == null || !mbd.isSynthetic()) {
wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);//初始化之前 执行所有后置处理器中的方法
}
try {
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()) {
wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName); //初始化之后 执行后置处理器中的方法
}
return wrappedBean;
}
initializeBean方法的工作流程:
- 执行Aware接口方法:invokeAwareMethods(beanName, bean);执行xxxAware接口的方法。
- 初始化之前执行后置处理器的postProcessBeforeInitialization()方法:applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
- 执行初始化方法:invokeInitMethods(beanName, wrappedBean, mbd);
- 初始化之后执行后置处理器的postProcessAfterInitialization()方法: applyBeanPostProcessorsAfterInitialization
下面来看看这几个过程的具体是实现方法:
invokeAwareMethods:
private void invokeAwareMethods(final String beanName, final Object bean) {
if (bean instanceof Aware) {
if (bean instanceof BeanNameAware) {
//在创建此bean的bean工厂中设置bean的名称。
((BeanNameAware) bean).setBeanName(beanName);
}
if (bean instanceof BeanClassLoaderAware) {
//回调函数将bean {@link ClassLoader类加载器}提供给bean实例。
((BeanClassLoaderAware) bean).setBeanClassLoader(getBeanClassLoader());
}
if (bean instanceof BeanFactoryAware) {
//将拥有的工厂提供给bean实例的回调。
((BeanFactoryAware) bean).setBeanFactory(AbstractAutowireCapableBeanFactory.this);
}
}
}
invokeAwareMethods方法执行了BeanNameAware接口的setBeanName()方法、BeanClassLoaderAware接口的setBeanClassLoader()方法、BeanFactoryAware接口的setBeanFactory()方法。
applyBeanPostProcessorsBeforeInitialization:
@Override
public Object applyBeanPostProcessorsBeforeInitialization(Object existingBean, String beanName)
throws BeansException {
Object result = existingBean;
for (BeanPostProcessor beanProcessor : getBeanPostProcessors()) {
result = beanProcessor.postProcessBeforeInitialization(result, beanName);
if (result == null) {
return result;
}
}
return result;
}
bean实例初始化之前,执行BeanPostProcessor后置处理器的postProcessBeforeInitialization()方法
invokeInitMethods:
protected void invokeInitMethods(String beanName, final Object bean, RootBeanDefinition mbd)
throws Throwable {
boolean isInitializingBean = (bean instanceof InitializingBean); //实现InitializingBean接口
if (isInitializingBean && (mbd == null || !mbd.isExternallyManagedInitMethod("afterPropertiesSet"))) {
if (logger.isDebugEnabled()) {
logger.debug("Invoking afterPropertiesSet() on bean with name '" + beanName + "'");
}
if (System.getSecurityManager() != null) {
try {
AccessController.doPrivileged(new PrivilegedExceptionAction<Object>() {
@Override
public Object run() throws Exception {
((InitializingBean) bean).afterPropertiesSet();
return null;
}
}, getAccessControlContext());
}catch (PrivilegedActionException pae) {
throw pae.getException();
}
}else {
((InitializingBean) bean).afterPropertiesSet();
}
}
if (mbd != null) {
String initMethodName = mbd.getInitMethodName(); //自定义初始化方法
if (initMethodName != null && !(isInitializingBean && "afterPropertiesSet".equals(initMethodName)) &&
!mbd.isExternallyManagedInitMethod(initMethodName)) {
invokeCustomInitMethod(beanName, bean, mbd);
}
}
}
invokeInitMethods执行的初始化方法,先检查bean是否实现InitializingBean接口,再检查bean是否有指定的初始化执行方法。
applyBeanPostProcessorsAfterInitialization:
public Object applyBeanPostProcessorsAfterInitialization(Object existingBean, String beanName)
throws BeansException {
Object result = existingBean;
for (BeanPostProcessor beanProcessor : getBeanPostProcessors()) {
result = beanProcessor.postProcessAfterInitialization(result, beanName);
if (result == null) {
return result;
}
}
return result;
}
bean初始化完成之后,执行BeanPostProcessor的postProcessAfterInitialization方法。
至此,bean的创建和初始化完成,返回处理好的bean实例。
doCreateBean方法创建好bean后,返回createBean()方法,createBean方法是在doGetBean方法的getSingleton方法中被调用:
sharedInstance = getSingleton(beanName, new ObjectFactory<Object>() {
@Override
public Object getObject() throws BeansException {
try {
return createBean(beanName, mbd, args);
}catch (BeansException ex) {
destroySingleton(beanName);
throw ex;
}
}
});
下面来看一下getSingleton方法中如何处理返回的创建好的bean实例:
public Object getSingleton(String beanName, ObjectFactory<?> singletonFactory) {
Assert.notNull(beanName, "'beanName' 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<Exception>();
}
try {
singletonObject = singletonFactory.getObject();
newSingleton = true;
}
catch (IllegalStateException ex) {
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) { //如果是新创建的单例bean,添加到singletonObject缓存中
addSingleton(beanName, singletonObject);
}
}
return (singletonObject != NULL_OBJECT ? singletonObject : null);
}
}
在方法最后:
if (newSingleton) {
addSingleton(beanName, singletonObject);
}
从这里可以看出,Spring容器会将新创建好的,并且初始化完成的单例bean,放到singletonObject缓存中,而singletonObject实际上是一个map集合队列。
再次回到上面提到的beanFactory.preInstantiateSingletons():方法中,getBean()方法执行完成,即bean创建和初始化完成后,返回的bean实例没有被接受,那是因为它已经被缓存到spring容器中,以后可以从容器中直接获取bean实例。