Spring源码(4)单例Bean的创建及初始化过程
前言
在前面的三篇文章中,我们了解IOC的初始化流程
这一篇,我们开始refresh方法中的finishBeanFactoryInitialization(beanFactory)方法。直接上代码:
/**
* Finish the initialization of this context's bean factory,
* initializing all remaining singleton beans.
*/
protected void finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory) {
// Initialize conversion service for this context.
//初始化上下文的转换服务,ConversionService是一个类型转换接口
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));
}
// Register a default embedded value resolver if no bean post-processor
// (such as a PropertyPlaceholderConfigurer bean) registered any before:
// at this point, primarily for resolution in annotation attribute values.
//设置一个字符串解析器
//设置一个内置的值处理器(若没有的话),该处理器作用有点像一个PropertyPlaceholderConfigurer bean
if (!beanFactory.hasEmbeddedValueResolver()) {
beanFactory.addEmbeddedValueResolver(strVal -> getEnvironment().resolvePlaceholders(strVal));
}
// Initialize LoadTimeWeaverAware beans early to allow for registering their transformers early.
//todo 获取类型为LoadTimeWeaverAware的bean name;(待理解)
String[] weaverAwareNames = beanFactory.getBeanNamesForType(LoadTimeWeaverAware.class, false, false);
for (String weaverAwareName : weaverAwareNames) {
getBean(weaverAwareName);
}
// Stop using the temporary ClassLoader for type matching.
beanFactory.setTempClassLoader(null);
// Allow for caching all bean definition metadata, not expecting further changes.
//拷贝BeanDefinitionNames 缓存到数组
beanFactory.freezeConfiguration();
// Instantiate all remaining (non-lazy-init) singletons.
//创建并初始化所有的singleton bean(non-lazy)
beanFactory.preInstantiateSingletons();
}
这个方法主要是为创建及初始化bean做准备,比如设置类型转换器,字符串在解析器等,这些都不是本章的重点,我们直接来到preInstantiateSingletons方法
public void preInstantiateSingletons() throws BeansException {
if (logger.isTraceEnabled()) {
logger.trace("Pre-instantiating singletons in " + this);
}
// Iterate over a copy to allow for init methods which in turn register new bean definitions.
// While this may not be part of the regular factory bootstrap, it does otherwise work fine.
//获取所有的beanDefinition Name
List<String> beanNames = new ArrayList<>(this.beanDefinitionNames);
// 也许你会觉得下面的代码不好理解,其实很简单,首先先判断是否为FactoryBean
// 如果是的话为beanName加上前缀&,调用getBean进行获取或创建得到bean
// 得到后判断factory instanceof SmartFactoryBean,是的话调用isEagerInit判断是否需要立即创建(也就是立即调用getObject方法)
for (String beanName : beanNames) {
//获取bean定义信息
RootBeanDefinition bd = getMergedLocalBeanDefinition(beanName);
if (!bd.isAbstract() && bd.isSingleton() && !bd.isLazyInit()) {
//判断是否为FactoryBean,创建两个实例,一个为&开头(FactoryBean),一个由getObject()的到bean
if (isFactoryBean(beanName)) {
//获取FactoryBean
Object bean = getBean(FACTORY_BEAN_PREFIX + beanName);
if (bean instanceof FactoryBean) {
FactoryBean<?> factory = (FactoryBean<?>) bean;
boolean isEagerInit;//是否立即实例化bean
if (System.getSecurityManager() != null && factory instanceof SmartFactoryBean) {
//AccessController.doPrivileged 有关权限的
isEagerInit = AccessController.doPrivileged(
(PrivilegedAction<Boolean>) ((SmartFactoryBean<?>) factory)::isEagerInit,
getAccessControlContext());
}
else {
isEagerInit = (factory instanceof SmartFactoryBean &&
((SmartFactoryBean<?>) factory).isEagerInit());
}
if (isEagerInit) {
getBean(beanName);
}
}
}
//不为FactoryBean的bean
else {
getBean(beanName);
}
}
}
// Trigger post-initialization callback for all applicable beans...
for (String beanName : beanNames) {
Object singletonInstance = getSingleton(beanName);
if (singletonInstance instanceof SmartInitializingSingleton) {
SmartInitializingSingleton smartSingleton = (SmartInitializingSingleton) singletonInstance;
if (System.getSecurityManager() != null) {
AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
smartSingleton.afterSingletonsInstantiated();
return null;
}, getAccessControlContext());
}
else {
smartSingleton.afterSingletonsInstantiated();
}
}
}
}
preInstantiateSingletons方法主要是遍历所有注册的beanName,对!bd.isAbstract() && bd.isSingleton() && !bd.isLazyInit()的bean进行创建及初始化。
我们先来看看RootBeanDefinition bd = getMergedLocalBeanDefinition(beanName); 这里为什么要讲它,因为后面很多地方都会用到
//先从缓存中拿,拿不到就获取
protected RootBeanDefinition getMergedLocalBeanDefinition(String beanName) throws BeansException {
// Quick check on the concurrent map first, with minimal locking.
RootBeanDefinition mbd = this.mergedBeanDefinitions.get(beanName);
if (mbd != null && !mbd.stale) {
return mbd;
}
//分为两步,第一步从BeanDefinitionMap中获取,第二部再进行合并
return getMergedBeanDefinition(beanName, getBeanDefinition(beanName));
}
//这个方法很容易,冲缓存中去获取,获取不到则抛异常
public BeanDefinition getBeanDefinition(String beanName) throws NoSuchBeanDefinitionException {
BeanDefinition bd = this.beanDefinitionMap.get(beanName);
if (bd == null) {
if (logger.isTraceEnabled()) {
logger.trace("No bean named '" + beanName + "' found in " + this);
}
throw new NoSuchBeanDefinitionException(beanName);
}
return bd;
}
//对父子进行合并,说实话这和在xml比较常用,注解的话,基本是用不到了
//总结一下就是
//合并父子BeanDefinition
//1:判断是否有父BeanDefinition
//2:如果没有,则克隆原来的BeanDefinition并返回
//3:如果有,则判断父子的name是否相同
//4:如果不相同,进行合并
//5:如果相同,这判断是否为父容器的BeanDefinition
//6:如果是,则获取并合并
//7:如果不是则抛异常
protected RootBeanDefinition getMergedBeanDefinition(
String beanName, BeanDefinition bd, @Nullable BeanDefinition containingBd)
throws BeanDefinitionStoreException {
synchronized (this.mergedBeanDefinitions) {
RootBeanDefinition mbd = null;
RootBeanDefinition previous = null;
// Check with full lock now in order to enforce the same merged instance.
if (containingBd == null) {
//从缓存中获取
mbd = this.mergedBeanDefinitions.get(beanName);
}
if (mbd == null || mbd.stale) {
previous = mbd;
//如果没有父BeanDefinition
if (bd.getParentName() == null) {
// Use copy of given root bean definition.
if (bd instanceof RootBeanDefinition) {
mbd = ((RootBeanDefinition) bd).cloneBeanDefinition();
}
else {
mbd = new RootBeanDefinition(bd);
}
}
//如果有父BeanDefinition
else {
// Child bean definition: needs to be merged with parent.
BeanDefinition pbd;
try {
//转换(这里可看出ParentName 也支持别名)
String parentBeanName = transformedBeanName(bd.getParentName());
//如果名字不相同,
if (!beanName.equals(parentBeanName)) {
pbd = getMergedBeanDefinition(parentBeanName);
}
//同一容器,同一父子beanDefinition会出现死循环
else {
BeanFactory parent = getParentBeanFactory();
//如果为parent不为null,且为ConfigurableBeanFactory及其子类,则去父容器获取
if (parent instanceof ConfigurableBeanFactory) {
pbd = ((ConfigurableBeanFactory) parent).getMergedBeanDefinition(parentBeanName);
}
//如果为null则报异常
else {
throw new NoSuchBeanDefinitionException(parentBeanName,
"Parent name '" + parentBeanName + "' is equal to bean name '" + beanName +
"': cannot be resolved without a ConfigurableBeanFactory parent");
}
}
}
catch (NoSuchBeanDefinitionException ex) {
throw new BeanDefinitionStoreException(bd.getResourceDescription(), beanName,
"Could not resolve parent bean definition '" + bd.getParentName() + "'", ex);
}
// Deep copy with overridden values.
mbd = new RootBeanDefinition(pbd);
mbd.overrideFrom(bd);
}
// Set default singleton scope, if not configured before.
if (!StringUtils.hasLength(mbd.getScope())) {
mbd.setScope(SCOPE_SINGLETON);
}
// A bean contained in a non-singleton bean cannot be a singleton itself.
// Let's correct this on the fly here, since this might be the result of
// parent-child merging for the outer bean, in which case the original inner bean
// definition will not have inherited the merged outer bean's singleton status.
if (containingBd != null && !containingBd.isSingleton() && mbd.isSingleton()) {
mbd.setScope(containingBd.getScope());
}
// Cache the merged bean definition for the time being
// (it might still get re-merged later on in order to pick up metadata changes)
if (containingBd == null && isCacheBeanMetadata()) {
this.mergedBeanDefinitions.put(beanName, mbd);
}
}
if (previous != null) {
copyRelevantMergedBeanDefinitionCaches(previous, mbd);
}
return mbd;
}
}
然后我们来看看getBean(beanName)方法
@Override
public Object getBean(String name) throws BeansException {
return doGetBean(name, null, null, false);
}
@Override
public <T> T getBean(String name, Class<T> requiredType) throws BeansException {
return doGetBean(name, requiredType, null, false);
}
@Override
public Object getBean(String name, Object... args) throws BeansException {
return doGetBean(name, null, args, false);
}
getBean有三个重载方法,不过里面都是调用了doGetBean方法
@SuppressWarnings("unchecked")
protected <T> T doGetBean(
String name, @Nullable Class<T> requiredType, @Nullable Object[] args, boolean typeCheckOnly)
throws BeansException {
// 转换为beanName,截掉&,截掉后,如果是别名则转化为实际的beanName
String beanName = transformedBeanName(name);
Object bean;
// Eagerly check singleton cache for manually registered singletons.
//从缓存中(重点)获取bean
Object sharedInstance = getSingleton(beanName);
//判断是否存在,为什么args要等于null 看上面spring doc
if (sharedInstance != null && args == null) {
if (logger.isTraceEnabled()) {
if (isSingletonCurrentlyInCreation(beanName)) {
logger.trace("Returning eagerly cached instance of singleton bean '" + beanName +
"' that is not fully initialized yet - a consequence of a circular reference");
}
else {
logger.trace("Returning cached instance of singleton bean '" + beanName + "'");
}
}
//判断是否为FactoryBean,如果不是的化直接返回,如果是的话,校验入参name是否为&开头,不是的话调用getObject方法
bean = getObjectForBeanInstance(sharedInstance, name, beanName, null);
}
else {
// Fail if we're already creating this bean instance:
// We're assumably within a circular reference.
//判断是scope否为Prototype类型,且在创建中
//所以说,prototype:不支持循环依赖
//singleton - prototype - singleton 可以
//prototype - singleton - prototype 抛异常
if (isPrototypeCurrentlyInCreation(beanName)) {
throw new BeanCurrentlyInCreationException(beanName);
}
// Check if bean definition exists in this factory.
//获取父工厂
BeanFactory parentBeanFactory = getParentBeanFactory();
//父上下文不为空且,当前上下文不包含该BeanDefinition
if (parentBeanFactory != null && !containsBeanDefinition(beanName)) {
// Not found -> check parent.
//获取原来的名字
String nameToLookup = originalBeanName(name);
//是否为AbstractBeanFactory或其子类
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 if (requiredType != null) {
// No args -> delegate to standard getBean method.
return parentBeanFactory.getBean(nameToLookup, requiredType);
}
else {
return (T) parentBeanFactory.getBean(nameToLookup);
}
}
//创建的Bean是否需要进行类型验证,一般不需要
if (!typeCheckOnly) {
//因为从缓存中拿不到bean,所以肯定不是创建的状态
//把bean标志位即将创建的状态
markBeanAsCreated(beanName);
}
try {
//根据指定Bean名称获取其父级的Bean定义
//主要解决Bean继承时子类合并父类公共属性问题
RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
//检查是否为抽象类
checkMergedBeanDefinition(mbd, beanName, args);
// Guarantee initialization of beans that the current bean depends on.
//获取DependsOn的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 + "'");
}
//保存bean所依赖的所有bean的名称
//保存被依赖的bean的名称
registerDependentBean(dep, beanName);
try {
//获取bean
getBean(dep);
}
catch (NoSuchBeanDefinitionException ex) {
throw new BeanCreationException(mbd.getResourceDescription(), beanName,
"'" + beanName + "' depends on missing bean '" + dep + "'", ex);
}
}
}
// Create bean instance.
//是否为Singleton
if (mbd.isSingleton()) {
//创建
sharedInstance = getSingleton(beanName, () -> {
try {
return createBean(beanName, mbd, args);
}
catch (BeansException ex) {
// Explicitly remove instance from singleton cache: It might have been put there
// eagerly by the creation process, to allow for circular reference resolution.
// Also remove any beans that received a temporary reference to the bean.
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();
if (!StringUtils.hasLength(scopeName)) {
throw new IllegalStateException("No scope name defined for bean ´" + beanName + "'");
}
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;
}
}
// Check if required type matches the type of the actual bean instance.
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) {
if (logger.isTraceEnabled()) {
logger.trace("Failed to convert bean '" + name + "' to required type '" +
ClassUtils.getQualifiedName(requiredType) + "'", ex);
}
throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass());
}
}
return (T) bean;
}
从源码中我们可以看出做了一下这几步:
- 转换beanName(这里为什么是入参进来的交Name,而转化后的叫beanName呢)其实就是因为事情&只是个标记而已,是用来判断是直接放回bean,还是返回执行bean.getObject()方法返回的bean。
- 尝试从缓存中获取bean
- 如果bean不为空,则判断是否为FactoryBean,是的话判断name 是否以&开头,是的话直接返回,不是的话返回执行getObject方法返回的bean。
- 如果bean为空,则根据不同的scope进程不同的bean创建
- 最后进行类型校验
我们先来看看String beanName = transformedBeanName(name); 方法
//截掉&,并获取真实的BeanName
protected String transformedBeanName(String name) {
//transformedBeanName(name) 如果是&开头的要截掉
//canonicalName(BeanFactoryUtils.transformedBeanName(name)) 如果是别名,则进行映射
return canonicalName(BeanFactoryUtils.transformedBeanName(name));
}
//如果不是start with &不用处理返回
//如果是截掉&,为什么要do while,因为可能出现这种情况:&&beanName,并保存到缓存中
public static String transformedBeanName(String name) {
Assert.notNull(name, "'name' must not be null");
if (!name.startsWith(BeanFactory.FACTORY_BEAN_PREFIX)) {
return name;
}
//将开头为& 截掉
//若取出的value为null,则保存新的bean并返回
return transformedBeanNameCache.computeIfAbsent(name, beanName -> {
do {
beanName = beanName.substring(BeanFactory.FACTORY_BEAN_PREFIX.length());
}
while (beanName.startsWith(BeanFactory.FACTORY_BEAN_PREFIX));
return beanName;
});
}
// 获取实际的bean name,因为传进来的可能是别名,为什么用do while
// 因为可能出现这种情况 A-> B ->C,意思是A是B的别名,B是C的别名
public String canonicalName(String name) {
String canonicalName = name;
// Handle aliasing...
String resolvedName;
do {
resolvedName = this.aliasMap.get(canonicalName);
if (resolvedName != null) {
canonicalName = resolvedName;
}
}
while (resolvedName != null);
return canonicalName;
}
接下来是Object sharedInstance = getSingleton(beanName); 循环依赖解决方案。现在看确实看的一头雾水,在后面介绍doCreateBean中在结合这个方法你就会明白。
代码很容易
public Object getSingleton(String beanName) {
return getSingleton(beanName, true);
}
protected Object getSingleton(String beanName, boolean allowEarlyReference) {
//从一级缓存获取bean
Object singletonObject = this.singletonObjects.get(beanName);
//如果bean为空且---bean在创建过程中(注意重点)---
if (singletonObject == null && isSingletonCurrentlyInCreation(beanName)) {
synchronized (this.singletonObjects) {
//从二级缓存获取bean
singletonObject = this.earlySingletonObjects.get(beanName);
//bean还是为空且允许创建早期引用
if (singletonObject == null && allowEarlyReference) {
//从三级缓存获取ObjectFactory(创建对象的函数)
ObjectFactory<?> singletonFactory = this.singletonFactories.get(beanName);
if (singletonFactory != null) {
//创建对象
singletonObject = singletonFactory.getObject();
//保存到二级缓存
this.earlySingletonObjects.put(beanName, singletonObject);
//从三级缓存移除
this.singletonFactories.remove(beanName);
}
}
}
}
return singletonObject;
}
无论什么情况返回的bean,都会调用getObjectForBeanInstance进行处理。
bean = getObjectForBeanInstance(sharedInstance, name, beanName, null);
//判断是否为FactoryBean,不是的话直接返回,是的话特殊处理
protected Object getObjectForBeanInstance(
Object beanInstance, String name, String beanName, @Nullable RootBeanDefinition mbd) {
// Don't let calling code try to dereference the factory if the bean isn't a factory.
//beanName 以&开头
if (BeanFactoryUtils.isFactoryDereference(name)) {
//这里什么时候为NullBean呢,据我所知getObject返回为null的话就是NullBean
if (beanInstance instanceof NullBean) {
return beanInstance;
}
//这里可以知道如果你不是FactoryBean类型有时&开头,那就异常
if (!(beanInstance instanceof FactoryBean)) {
throw new BeanIsNotAFactoryException(beanName, beanInstance.getClass());
}
if (mbd != null) {
mbd.isFactoryBean = true;
}
return beanInstance;
}
// Now we have the bean instance, which may be a normal bean or a FactoryBean.
// If it's a FactoryBean, we use it to create a bean instance, unless the
// caller actually wants a reference to the factory.
if (!(beanInstance instanceof FactoryBean)) {
return beanInstance;
}
Object object = null;
if (mbd != null) {
mbd.isFactoryBean = true;
}
else {
//从缓存中获取bean,这里的缓存是装们保存getObject 中的bean
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());
//下面会讲
object = getObjectFromFactoryBean(factory, beanName, !synthetic);
}
return object;
}
//getObjectFromFactoryBean
protected Object getObjectFromFactoryBean(FactoryBean<?> factory, String beanName, boolean shouldPostProcess) {
if (factory.isSingleton() && containsSingleton(beanName)) {
synchronized (getSingletonMutex()) {
//尝试从缓存中获取
Object object = this.factoryBeanObjectCache.get(beanName);
if (object == null) {
//调用getObject并返回
object = doGetObjectFromFactoryBean(factory, beanName);
// Only post-process and store if not put there already during getObject() call above
// (e.g. because of circular reference processing triggered by custom getBean calls)
// 有可能当执行doGetObjectFromFactoryBean函数时,Bean正在创建,所以此时再获取一下(网上的答案,现在还是不明白为什么)
Object alreadyThere = this.factoryBeanObjectCache.get(beanName);
if (alreadyThere != null) {
object = alreadyThere;
}
else {
if (shouldPostProcess) {
if (isSingletonCurrentlyInCreation(beanName)) {
// Temporarily return non-post-processed object, not storing it yet..
return object;
}
//标志位创建状态
beforeSingletonCreation(beanName);
try {
//初始化后后置处理回调
object = postProcessObjectFromFactoryBean(object, beanName);
}
catch (Throwable ex) {
throw new BeanCreationException(beanName,
"Post-processing of FactoryBean's singleton object failed", ex);
}
finally {
//移除创建中的状态
afterSingletonCreation(beanName);
}
}
if (containsSingleton(beanName)) {
this.factoryBeanObjectCache.put(beanName, object);
}
}
}
return object;
}
}
else {
Object object = doGetObjectFromFactoryBean(factory, beanName);
if (shouldPostProcess) {
try {
object = postProcessObjectFromFactoryBean(object, beanName);
}
catch (Throwable ex) {
throw new BeanCreationException(beanName, "Post-processing of FactoryBean's object failed", ex);
}
}
return object;
}
}
private Object doGetObjectFromFactoryBean(FactoryBean<?> factory, String beanName) throws BeanCreationException {
Object object;
try {
if (System.getSecurityManager() != null) {
AccessControlContext acc = getAccessControlContext();
try {
object = AccessController.doPrivileged((PrivilegedExceptionAction<Object>) factory::getObject, acc);
}
catch (PrivilegedActionException pae) {
throw pae.getException();
}
}
else {
object = factory.getObject();
}
}
catch (FactoryBeanNotInitializedException ex) {
throw new BeanCurrentlyInCreationException(beanName, ex.toString());
}
catch (Throwable ex) {
throw new BeanCreationException(beanName, "FactoryBean threw exception on object creation", ex);
}
// Do not accept a null value for a FactoryBean that's not fully
// initialized yet: Many FactoryBeans just return null then.
if (object == null) {
if (isSingletonCurrentlyInCreation(beanName)) {
throw new BeanCurrentlyInCreationException(
beanName, "FactoryBean which is currently in creation returned null from getObject");
}
//如果getObject is null ,那么就返回NullBean
object = new NullBean();
}
return object;
}
代码虽然很多,但是逻辑很简单,简单的讲,就是判断是否为FactoryBean类型不是的话直接返回,不是的话判断name(不是beanName)是否start with & 是的话直接返回,不是的话。调用getObject方法返回
getSingleton(String beanName, ObjectFactory<?> singletonFactory) 方法:
sharedInstance = getSingleton(beanName, () -> {
try {
return createBean(beanName, mbd, args);
}
catch (BeansException ex) {
// Explicitly remove instance from singleton cache: It might have been put there
// eagerly by the creation process, to allow for circular reference resolution.
// Also remove any beans that received a temporary reference to the bean.
destroySingleton(beanName);
throw ex;
}
})
public Object getSingleton(String beanName, ObjectFactory<?> singletonFactory) {
Assert.notNull(beanName, "Bean name 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<>();
}
try {
//创建bean
singletonObject = singletonFactory.getObject();
newSingleton = true;
}
catch (IllegalStateException ex) {
// Has the singleton object implicitly appeared in the meantime ->
// if yes, proceed with it since the exception indicates that state.
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) {
//添加到一级缓存
addSingleton(beanName, singletonObject);
}
}
return singletonObject;
}
}
这里面做了什么操作呢,
- 尝试从缓存中获取
- 标志为创建中的状态
- 调动creditBean方法获得bean
- 保存到一级缓存
下面我们讲creditBean方法
@Override
protected Object createBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)
throws BeanCreationException {
if (logger.isTraceEnabled()) {
logger.trace("Creating instance of bean '" + beanName + "'");
}
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.forName初始化类,并获取Class对象
//如果使用的是xml的话需要调用class.forName,注解的方式则不用
Class<?> resolvedClass = resolveBeanClass(mbd, beanName);
if (resolvedClass != null && !mbd.hasBeanClass() && mbd.getBeanClassName() != null) {
mbdToUse = new RootBeanDefinition(mbd);
mbdToUse.setBeanClass(resolvedClass);
}
// Prepare method overrides.
try {
//标记是不是为重载的方法,减小系统的开销(Lookup methodReplace的方法也保存再这里)
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的回调接口创建bean
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;
}
catch (BeanCreationException | ImplicitlyAppearedSingletonException ex) {
// A previously detected exception with proper bean creation context already,
// or illegal singleton state to be communicated up to DefaultSingletonBeanRegistry.
throw ex;
}
catch (Throwable ex) {
throw new BeanCreationException(
mbdToUse.getResourceDescription(), beanName, "Unexpected exception during bean creation", ex);
}
}
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()) {
//获取类型 getTargetClass
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;
}
protected Object doCreateBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)
throws BeanCreationException {
// Instantiate the bean.
//BeanWrapper,可以对包装的bean进行操作
BeanWrapper instanceWrapper = null;
if (mbd.isSingleton()) {
//*(还不明白),这里的意义,factoryBeanInstanceCache:保存了FactoryBean的BeanWrapper
instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);
}
if (instanceWrapper == null) {
//创建实例,并用BeanWrapper进行包装
//
// 创建 bean 实例,并将实例包裹在 BeanWrapper 实现类对象中返回。
// createBeanInstance中包含三种创建 bean 实例的方式:
// 1. 通过工厂方法创建 bean 实例
// 2. 通过构造方法自动注入(autowire by constructor)的方式创建 bean 实例
// 3. 通过无参构造方法方法创建 bean 实例
//
// 若 bean 的配置信息中配置了 lookup-method 和 replace-method,则会使用 CGLIB 增强 bean 实例。
//
instanceWrapper = createBeanInstance(beanName, mbd, args);
}
//获取实例
Object bean = instanceWrapper.getWrappedInstance();
//获取class对象
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().postProcessMergedBeanDefinition进行回调操作
//可以对合并后的BeanDefinition进行操作,例如保存@PostConstruct,@PreDestroy,@Resource,@Autowride @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;
}
}
// Eagerly cache singletons to be able to resolve circular references
// even when triggered by lifecycle interfaces like BeanFactoryAware.
//是否允许提前暴露
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");
}
//保存到三级缓存
//这里的getEarlyBeanReference(beanName, mbd, bean),
//这里对bean实例进行提前暴露处理处理,对SmartInstantiationAwareBeanPostProcessor().getEarlyBeanReference进行回调
addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean));
}
// Initialize the bean instance.
Object exposedObject = bean;
try {
//填充属性
populateBean(beanName, mbd, instanceWrapper);
//1、执行aware回调
//2、执行postProcessBeforeInitialization (@PostConstructor)
//3、执行init
//4、执行postProcessAfterInitialization
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);
}
}
//这里涉及到Aop,我们会在其他文章进行讲解
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<>(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 " +
"'getBeanNamesForType' with the 'allowEagerInit' flag turned off, for example.");
}
}
}
}
// Register bean as disposable.
try {
registerDisposableBeanIfNecessary(beanName, bean, mbd);
}
catch (BeanDefinitionValidationException ex) {
throw new BeanCreationException(
mbd.getResourceDescription(), beanName, "Invalid destruction signature", ex);
}
return exposedObject;
}
之后具体的细节我们重新启用其他的文章单独讲,包括实例的创建,以及属性的填充,包括aop代理。
回顾并总结
整个单例bean的创建及初始化过程,主要逻辑基本在doGetBean和doCreateBean中
doGetBean
- 尝试从缓存中获取bean
- 获取到则进行FactoryBean校验及处理
- 如果获取不到,则根据不同的socpe进行不同的bean的创建流程(doCreateBean)
- 类型的校验及转换
doCreateBean
- 将beanName标记为创建中的状态,
- 尝试提前创建实例和初始化(有则返回,没有则进行下一步)
- 创建实例
- 回调applyMergedBeanDefinitionPostProcessors(mbd, beanType,
beanName)(其实就是解析@PostConstruct,@PreDestroy,@Resource,@Autowride
@Value等放到缓存中) - 保存到三级缓存
- 填充属性
- 初始化