Spring源码系列文章
Spring源码解析(一):环境搭建
Spring源码解析(二):bean容器的创建、默认后置处理器、扫描包路径bean
Spring源码解析(三):bean容器的刷新
Spring源码解析(四):单例bean的创建流程
@Override
public void preInstantiateSingletons() throws BeansException {
if (logger.isTraceEnabled()) {
logger.trace("Pre-instantiating singletons in " + this);
}
// 创建beanDefinitionNames的副本beanNames用于后续的遍历,以允许init等方法注册新的bean定义
List<String> beanNames = new ArrayList<>(this.beanDefinitionNames);
// 所有非懒加载单例bean的初始化
for (String beanName : beanNames) {
// 获取合并后的bean定义信息
RootBeanDefinition bd = getMergedLocalBeanDefinition(beanName);
// bean定义对应的Bean实例:不是抽象类 && 是单例 && 不是懒加载
if (!bd.isAbstract() && bd.isSingleton() && !bd.isLazyInit()) {
// 判断beanName对应的bean是否为FactoryBean
if (isFactoryBean(beanName)) {
// 通过getBean(&beanName)拿到的是FactoryBean本身;
// 通过getBean(beanName)拿到的是FactoryBean创建的Bean实例
// FACTORY_BEAN_PREFIX = "&";
Object bean = getBean(FACTORY_BEAN_PREFIX + beanName);
// 判断bean是否实现了FactoryBean
if (bean instanceof FactoryBean) {
final FactoryBean<?> factory = (FactoryBean<?>) bean;
//判断是否需要立即创建FactoryBean中的bean
boolean isEagerInit;
if (System.getSecurityManager() != null && factory instanceof SmartFactoryBean) {
isEagerInit = AccessController.doPrivileged((PrivilegedAction<Boolean>)
((SmartFactoryBean<?>) factory)::isEagerInit,
getAccessControlContext());
}
else {
isEagerInit = (factory instanceof SmartFactoryBean &&
((SmartFactoryBean<?>) factory).isEagerInit());
}
if (isEagerInit) {
// 如果希望马上初始化,则通过beanName获取bean实例
getBean(beanName);
}
}
}
else {
// 如果beanName对应的bean不是FactoryBean,只是普通Bean,通过beanName获取bean实例
getBean(beanName);
}
}
}
// 在所有bean实例化后,遍历所有beanName
// 触发所有SmartInitializingSingleton实例化后后置处理器方法afterSingletonsInstantiated();
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();
}
}
}
}
FactoryBean
public interface FactoryBean<T> {
/**
* 返回此工厂管理的对象的实例
*/
@Nullable
T getObject() throws Exception;
/**
* 返回此 FactoryBean 创建的对象类型
*/
@Nullable
Class<?> getObjectType();
/**
* 此工厂管理的对象是否单实例
*/
default boolean isSingleton() {
return true;
}
}
复杂
的对象&
beanName)拿到的是FactoryBean本身总结
doGetBean方法大致流程
进入doGetBean方法
protected <T> T doGetBean(final String name, @Nullable final Class<T> requiredType,
@Nullable final Object[] args, boolean typeCheckOnly) throws BeansException {
//通过三种形式获取beanName
//一个是原始的beanName,一个是加了&的,一个是别名
final String beanName = transformedBeanName(name);
Object bean;
// 1、从缓存中获取beanName对应的实例
// Spring创建bean的原则是不等bean创建完成就会将创建bean的ObjectFactory提早曝光
// 如果存在循环依赖, 那么缓存中存在, 存在的对象是2种情况: 1)未属性注入的普通bean 2)经过AOP的代理对象
Object sharedInstance = getSingleton(beanName);
// 缓存获取到以后,必须参数为空才行,不然参数不同,获取到的肯定不一样
if (sharedInstance != null && args == null) {
if (logger.isTraceEnabled()) {
// 如果beanName的实例存在于缓存中,且Bean还在创建中,则说明是循环引用
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 + "'");
}
}
// 2、如果是普通bean,直接返回,如果是FactoryBean,则返回它的getObject
bean = getObjectForBeanInstance(sharedInstance, name, beanName, null);
}
// 缓存中还不存在bean,或者有bean但是args参数进入此方法
else {
// 如果scope为prototype并且 显示还在创建中,则基本是循环依赖的情况
// 针对prototype的循环依赖,spring无解,直接抛出异常
// 例子:如果存在A中有B的属性,B中有A的属性,那么当依赖注入的时候,
// 就会产生当A还未创建完的时候因为对于B的创建再次返回创建A,造成循环依赖
if (isPrototypeCurrentlyInCreation(beanName)) {
throw new BeanCurrentlyInCreationException(beanName);
}
// 获取parentBeanFactory(父容器)
BeanFactory parentBeanFactory = getParentBeanFactory();
// 从当前容器中找不到指定名称的bean,此时递归去parentFactory查找
if (parentBeanFactory != null && !containsBeanDefinition(beanName)) {
// 主要针对FactoryBean,将Bean的&重新加上
String nameToLookup = originalBeanName(name);
// 如果parent容器依旧是AbstractBeanFactory的实例
// instanceof通过返回一个布尔值来指出,这个对象是否是这个特定类或者是它的子类的一个实例
if (parentBeanFactory instanceof AbstractBeanFactory) {
// 直接递归调用doGetBean方法来查找
return ((AbstractBeanFactory) parentBeanFactory).doGetBean(
nameToLookup, requiredType, args, typeCheckOnly);
}
else if (args != null) {
// 如果有参数,则委派父类容器根据指定名称和显示的参数查找
return (T) parentBeanFactory.getBean(nameToLookup, args);
}
else if (requiredType != null) {
// 委派父级容器根据指定名称和类型查找
return parentBeanFactory.getBean(nameToLookup, requiredType);
}
else {
// 委派父级容器根据指定名称查找
return (T) parentBeanFactory.getBean(nameToLookup);
}
}
//typeCheckOnly是用来判断调用getBean()是否仅仅是为了类型检查获取bean,而不是为了创建Bean
if (!typeCheckOnly) {
// 如果不是仅仅做类型检查则是创建bean
// 将 Bean 标记为已创建
markBeanAsCreated(beanName);
}
try {
// 将父类的BeanDefinition与子类的BeanDefinition进行合并覆盖
final RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
// 对合并的BeanDefinition做验证,主要看属性是否为abstract的
checkMergedBeanDefinition(mbd, beanName, args);
// 拿到当前bean依赖的bean名称集合,在实例化自己之前,需要先实例化自己依赖的bean
String[] dependsOn = mbd.getDependsOn();
//如果当前Bean设置了dependsOn的属性
//depends-on用来指定Bean初始化及销毁时的顺序
//
//
if (dependsOn != null) {
//遍历当前bean依赖的bean名称集合
for (String dep : dependsOn) {
//3、检查dep是否依赖于beanName,即检查是否存在循环依赖
// 这里主要是判断是否有以下这种类型的依赖:
//
//
// 如果有,直接抛出异常
if (isDependent(beanName, dep)) {
throw new BeanCreationException(mbd.getResourceDescription(), beanName,
"Circular depends-on relationship between '" + beanName + "' and '" + dep + "'");
}
//4、将dep和beanName的依赖关系注册到缓存中
// 为给定的beanName注册一个依赖的dep,在给定的beanName被销毁之前销毁
registerDependentBean(dep, beanName);
try {
// 获取dep对应的bean实例,如果dep还没有创建bean实例,则创建dep的bean实例
getBean(dep);
}
catch (NoSuchBeanDefinitionException ex) {
throw new BeanCreationException(mbd.getResourceDescription(), beanName,
"'" + beanName + "' depends on missing bean '" + dep + "'", ex);
}
}
}
// 针对不同的scope进行bean的创建
if (mbd.isSingleton()) {
//5、单例bean创建(新建了一个ObjectFactory,并且重写了getObject方法)
sharedInstance = getSingleton(beanName, () -> {
try {
// 创建Bean实例
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.
// 显示从单例缓存中删除bean实例
// 因为单例模式下为了解决循环依赖,可能它已经存在了,所有将其销毁
destroySingleton(beanName);
throw ex;
}
});
// 如果是普通bean,直接返回,如果是FactoryBean,则返回它的getObject
bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
}
else if (mbd.isPrototype()) {
// 6、多例的bean创建
Object prototypeInstance = null;
try {
// 创建实例前的操作(将beanName保存到prototypesCurrentlyInCreation缓存中)
// 原型创建前的回调。将原型注册为当前正在创建
beforePrototypeCreation(beanName);
// 创建Bean实例
prototypeInstance = createBean(beanName, mbd, args);
}
finally {
// 创建实例后的操作(将创建完的beanName从prototypesCurrentlyInCreation缓存中移除)
// 原型创建后的回调。默认实现将原型标记为不在创建中
afterPrototypeCreation(beanName);
}
//beanName对应的实例对象
bean = getObjectForBeanInstance(prototypeInstance, name, beanName, mbd);
}
else {
// 剩余scope类型的bean创建,用的很少,如:request、session、application等生命周期
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 {
//其他scope的bean创建(新建了一个ObjectFactory,并且重写了getObject方法)
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;
}
}
// 检查所需类型是否与实际的bean对象的类型匹配
// 创建出来一个子类,但实际需要父类类型,多态转换
if (requiredType != null && !requiredType.isInstance(bean)) {
try {
// 类型不对,则尝试转换bean类型
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;
}
ObjectFactory提早曝光
1)未属性注入的普通bean
2)经过AOP的代理对象
ObjectFactory
/**
* 此类的实现通常意味着作为 API 提供给其他 bean(通过注入)
*/
@FunctionalInterface
public interface ObjectFactory<T> {
/**
* 返回此工厂管理的对象的实例
*/
T getObject() throws BeansException;
}
引入bean容器3个重要缓存
完整
对象半成品
对象工厂方法
,返回代理或原始对象//一级缓存(beanName->单例bean对象)单例对象的缓存
private final Map<String, Object> singletonObjects = new ConcurrentHashMap<>(256);
//二级缓存(beanName_>单例bean对象,对象还未进行属性填充、初始化)提前曝光的单例对象的缓存
//又称为早期单例对象,是因为earlySingletonObjects里的对象的都是通过提前曝光的ObjectFactory创建出来的,还未进行属性填充等操作
private final Map<String, Object> earlySingletonObjects = new HashMap<>(16);
//三级缓存(beanName->ObjectFactory 通过beanName获取单例bean工厂)单例对象工厂的缓存
private final Map<String, ObjectFactory<?>> singletonFactories = new HashMap<>(16);
// 当前正在创建单例bean对象的beanName集合
// 单例对象实例化成功前后,会将bean放入singletonsCurrentlyInCreation,也就是单例bean创建中
private final Set<String> singletonsCurrentlyInCreation =
Collections.newSetFromMap(new ConcurrentHashMap<>(16));
@Nullable
protected Object getSingleton(String beanName, boolean allowEarlyReference) {
// 从一级缓存单例池中获取单例对象
Object singletonObject = this.singletonObjects.get(beanName);
// 单例池没有并且当前beanname以及标记为正在创建中(出现了循环依赖)
// 单例对象实例化成功前后,会将bean放入singletonsCurrentlyInCreation,也就是单例bean创建中
if (singletonObject == null && isSingletonCurrentlyInCreation(beanName)) {
synchronized (this.singletonObjects) {
// 尝试从二级缓存获取(未创建完成的bean对象)
singletonObject = this.earlySingletonObjects.get(beanName);
// 如果二级缓存也没有,并且允许bean对象提前曝光引用
if (singletonObject == null && allowEarlyReference) {
// 从三级缓存中获取beanName的单例工厂
ObjectFactory<?> singletonFactory = this.singletonFactories.get(beanName);
if (singletonFactory != null) {
// 如果存在单例对象工厂,则通过工厂创建一个单例对象
// 存在AOP返回代理对象,否则返回原始对象
singletonObject = singletonFactory.getObject();
// 重点:将这个对象放入二级缓存中
this.earlySingletonObjects.put(beanName, singletonObject);
// 移除该beanName对应的单例对象工厂
// 因为该单例工厂已经创建了一个实例对象,并且放到二级缓存中
// 所以,后续获取beanName的单例对象,
// 可以通过二级缓存拿到,不需要在用到该单例工厂
this.singletonFactories.remove(beanName);
}
}
}
}
return singletonObject; //返回对象
}
缓存中获取bean对象总结
name
名称带&
,则代表获取的FactoryBean
本身,需要判断一下类型,然后返回普通的bean
,直接返回即可FactoryBean
,并且名称没有&
,需要通过FactoryBean#getObject()
获取对应的实例protected Object getObjectForBeanInstance(
Object beanInstance, String name, String beanName, @Nullable RootBeanDefinition mbd) {
// 第一种情况,名称带&,则获取的FactoryBean本身
if (BeanFactoryUtils.isFactoryDereference(name)) {
if (beanInstance instanceof NullBean) {
return beanInstance;
}
// 如果name以“&”为前缀,但是beanInstance不是FactoryBean,则抛异常
if (!(beanInstance instanceof FactoryBean)) {
throw new BeanIsNotAFactoryException(beanName, beanInstance.getClass());
}
}
// 第二种情况,代表是普通的bean,直接返回即可
if (!(beanInstance instanceof FactoryBean) || BeanFactoryUtils.isFactoryDereference(name)) {
return beanInstance;
}
// 到这里说明name不是以&开头,并且bean是FactoryBean类型的了
// 第三种情况,通过FactoryBean获取对应的实例
Object object = null;
if (mbd == null) {
// mdb此次调用传入的是空
// 尝试从缓存中获取,第一次肯定是空,下面获取成功会放入factoryBeanObjectCache缓存
object = getCachedObjectForFactoryBean(beanName);
}
if (object == null) {
// 只有beanInstance是FactoryBean才能走到这边,因此直接强转
FactoryBean<?> factory = (FactoryBean<?>) beanInstance;
// mbd为空,也就是所有已经加载的类中检测是否定义beanName
if (mbd == null && containsBeanDefinition(beanName)) {
// 如果有则把GenericBeanDefinition转为RootBeanDefinition,
// 如果指定的beanName是子bean的化,同时会合并父类的相关属性
mbd = getMergedLocalBeanDefinition(beanName);
}
// 是否用户定义的而不是应用程序本身定义的
boolean synthetic = (mbd != null && mbd.isSynthetic());
// 从FactoryBean获取对象实例
object = getObjectFromFactoryBean(factory, beanName, !synthetic);
}
return object;
}
FactoryBean
获取bean实例,这个最底层肯定是调用getObject()
方法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) {
// 缓存中无,这个方法的核心是调用了factoryBean的getObject
object = doGetObjectFromFactoryBean(factory, beanName);
// 得到之后,再尝试从缓存中获取
Object alreadyThere = this.factoryBeanObjectCache.get(beanName);
if (alreadyThere != null) {
// 如果此时缓存中有了,就直接取缓存中的值,避免循环依赖重复创建
object = alreadyThere;
}
else {
// 如果缓存中没有,则先判断需不需要执行后处理器
if (shouldPostProcess) {
// 如果当前bean正在创建中,则不需要执行,
// 因为产生了循环依赖,所以才会进入这里,当前bean还没有创建完成
// 等到bean创建完成之后,还会再进行处理的.
if (isSingletonCurrentlyInCreation(beanName)) {
// Temporarily return non-post-processed object, not storing it yet..
return object;
}
// 把beanName加入到singletonsCurrentlyInCreation中
// 记录加载状态.上面那个判断也是根绝这个集合来判断的
beforeSingletonCreation(beanName);
try {
// 执行后处理器
object = postProcessObjectFromFactoryBean(object, beanName);
}
catch (Throwable ex) {
throw new BeanCreationException(beanName,
"Post-processing of FactoryBean's singleton object failed", ex);
}
finally {
// 把beanName从singletonsCurrentlyInCreation中移除
// 即结束bean的加载状态
afterSingletonCreation(beanName);
}
}
if (containsSingleton(beanName)) {
// 添加缓存,如果是循环依赖的话,这里依旧没有加入缓存
this.factoryBeanObjectCache.put(beanName, object);
}
}
}
return object;
}
}
else {
// 如果不是单例,直接调用factoryBean的getObject方法即可
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;
}
}
depend-on
是bean的一个属性,表示当前 bean 是否要在其它 bean 之后加载正在创建中
不在创建中
createBean()
就是在两者之间创建的public Object getSingleton(String beanName, ObjectFactory<?> singletonFactory) {
Assert.notNull(beanName, "Bean name must not be null");
// 加锁,避免重复创建单例对象
synchronized (this.singletonObjects) {
// 首先检查beanName对应的bean实例是否在缓存中存在,如果已经存在,则直接返回
Object singletonObject = this.singletonObjects.get(beanName);
if (singletonObject == null) {
if (this.singletonsCurrentlyInDestruction) {
// 缓存中不存在,且bean工厂的单例处于destruction状态时,不允许进行单例bean创建,报错
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 {
// 执行singletonFactory的getObject方法获取bean实例
//【在这里通过createBean()创建实例,singletonFactory是传进来的函数式接口】
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) {
// 将beanName和singletonObject的映射关系添加到该工厂的单例缓存中
addSingleton(beanName, singletonObject);
}
}
return singletonObject;
}
}
addSingleton 新创建对象,添加到缓存
protected void addSingleton(String beanName, Object singletonObject) {
synchronized (this.singletonObjects) {
// 添加一级缓存(单例缓存对象)
this.singletonObjects.put(beanName, singletonObject);
// 删除三级缓存/单例工厂缓存(已经不需要)
this.singletonFactories.remove(beanName);
// 删除二级缓存/早期单例缓存,没有属性填充(已经不需要)
this.earlySingletonObjects.remove(beanName);
// 添加到已经注册的单例对象缓存
this.registeredSingletons.add(beanName);
}
}
获取单例bean的核心实现其实就是singletonObject = singletonFactory.getObject();
sharedInstance = getSingleton(beanName, () -> {
try {
// 创建Bean实例
return createBean(beanName, mbd, args);
} catch (BeansException ex) {
// 显示从单例缓存中删除bean实例
// 因为单例模式下为了解决循环依赖,可能它已经存在了,所有将其销毁
destroySingleton(beanName);
throw ex;
}
});
createBean方法大致流程
进入createBean方法
@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;
// 根据bean定义信息和bean名称解析得到bean的Class类型
Class<?> resolvedClass = resolveBeanClass(mbd, beanName);
if (resolvedClass != null && !mbd.hasBeanClass() && mbd.getBeanClassName() != null) {
// 如果resolvedClass存在,并且mdb的beanClass类型不是Class,并且mdb的beanClass不为空(则代表beanClass存的是Class的name),
// 则使用mdb深拷贝一个新的RootBeanDefinition副本,并且将解析的Class赋值给拷贝的RootBeanDefinition副本的beanClass属性,
// 该拷贝副本取代mdb用于后续的操作
mbdToUse = new RootBeanDefinition(mbd);
mbdToUse.setBeanClass(resolvedClass);
}
// 验证并准备为此bean定义的方法覆盖
// 主要为lookup-method,replace-method等配置准备
try {
mbdToUse.prepareMethodOverrides();
}
catch (BeanDefinitionValidationException ex) {
throw new BeanDefinitionStoreException(mbdToUse.getResourceDescription(),
beanName, "Validation of method overrides failed", ex);
}
try {
// 如果直接生成了一个Bean,就直接返回不走正常创建流程
// 给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实例(真正创建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);
}
}
总结
Class.forName("类全限定名")
doCreateBean()
doCreateBean方法大致流程
进入doCreateBean方法
protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final @Nullable Object[] args)
throws BeanCreationException {
// BeanWrapper封装了具体的Bean实例
// 然后可以很方便地通过调用getPropertyValue和setPropertyValue等方法反射读写Bean的具体属性
// 这个BeanWrapper是用来持有创建出来的bean对象的
BeanWrapper instanceWrapper = null;
if (mbd.isSingleton()) {
// 如果是单例对象,从factorybean实例缓存中获取 并且 移除当前bean定义信息
instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);
}
if (instanceWrapper == null) {
//创建bean的时候,这里创建bean的实例有三种方法
//1.工厂方法创建
//2.构造方法的方式注入
//3.无参构造方法注入
instanceWrapper = createBeanInstance(beanName, mbd, args);
}
// 从包装类中获取原始bean
final Object bean = instanceWrapper.getWrappedInstance();
// 获取具体的bean对象的Class属性
Class<?> beanType = instanceWrapper.getWrappedClass();
// 如果不等于NullBean类型,那么修改目标类型
if (beanType != NullBean.class) {
mbd.resolvedTargetType = beanType;
}
// 允许后置处理器修改合并的bean的定义信息
synchronized (mbd.postProcessingLock) {
if (!mbd.postProcessed) {
try {
// 应用后置处理器MergedBeanDefinitionPostProcessor,允许修改MergedBeanDefinition,
// @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正在创建中
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) = ObjectFactory
// 这里是一个匿名内部类,为了防止循环引用,尽早持有对象的引用
// 将还没完全配置好的bean存入到三级缓存中供其他bean使用(暴露引用)
// 这里的getEarlyBeanReference()方法,并不是在此调用,而是声明好了方法
// 具体调用在从缓存中获取单例对象时候调用
addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean));
}
// 初始化bean实例
Object exposedObject = bean;
try {
// 对bean进行属性填充;其中,可能存在依赖于其他bean的属性,则会递归初始化依赖的bean实例
populateBean(beanName, mbd, instanceWrapper);
// 初始化beanName
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);
// earlySingletonReference只有在当前解析的bean存在循环依赖的情况下才会不为空
if (earlySingletonReference != null) {
if (exposedObject == bean) {
// 如果exposedObject没有在initializeBean方法中被增强,则不影响之前的循环引用
exposedObject = earlySingletonReference;
}
// 解决dependent-on循环依赖问题
else if (!this.allowRawInjectionDespiteWrapping && hasDependentBean(beanName)) {
// 如果exposedObject在initializeBean方法中被增强
// && 不允许在循环引用的情况下使用注入原始bean实例
// && 当前bean有被其他bean依赖
// 拿到依赖当前bean的所有bean的beanName数组
String[] dependentBeans = getDependentBeans(beanName);
Set<String> actualDependentBeans = new LinkedHashSet<>(dependentBeans.length);
for (String dependentBean : dependentBeans) {
// 尝试移除这些bean的实例,因为这些bean依赖的bean已经被增强了,他们依赖的bean相当于脏数据
if (!removeSingletonIfCreatedForTypeCheckOnly(dependentBean)) {
//移除失败的添加到 actualDependentBeans
actualDependentBeans.add(dependentBean);
}
}
if (!actualDependentBeans.isEmpty()) {
// 如果存在移除失败的,则抛出异常,因为存在bean依赖了“脏数据”
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.");
}
}
}
}
// Register bean as disposable.
try {
//注册用于销毁的bean,执行销毁操作的有三种:
//自定义destroy方法、
//DisposableBean接口、
//DestructionAwareBeanPostProcessor
registerDisposableBeanIfNecessary(beanName, bean, mbd);
}
catch (BeanDefinitionValidationException ex) {
throw new BeanCreationException(
mbd.getResourceDescription(), beanName, "Invalid destruction signature", ex);
}
// 完成创建并返回
return exposedObject;
}
实例化bean
,通过不同的策略(工厂方法、构造方法、无参构造
)
protected BeanWrapper createBeanInstance(String beanName, RootBeanDefinition mbd, @Nullable Object[] args) {
// 解析bean的Class类型信息
Class<?> beanClass = resolveBeanClass(mbd, beanName);
// 如果bean的Class类型不为空、bean不是public修饰的、且bean不允许访问非公共构造函数和方法,那么Spring会抛异常
if (beanClass != null && !Modifier.isPublic(beanClass.getModifiers()) && !mbd.isNonPublicAccessAllowed()) {
throw new BeanCreationException(mbd.getResourceDescription(), beanName,
"Bean class isn't public, and non-public access not allowed: " + beanClass.getName());
}
// 通过Supplier实例化
// 判断当前beanDefinition中是否包含实例供应器,此处相当于一个回调方法,利用回调方法来创建bean
Supplier<?> instanceSupplier = mbd.getInstanceSupplier();
if (instanceSupplier != null) {
return obtainFromSupplier(instanceSupplier, beanName);
}
// 如果工厂方法不为空则使用工厂方法初始化策略
// 通过工厂方法实例化,即设置了factory-method,则使用工厂方法进行实例化
if (mbd.getFactoryMethodName() != null) {
return instantiateUsingFactoryMethod(beanName, mbd, args);
}
// 缓存机制, (一般单例用不到,多例的适合才用到缓存)
// 一个类可能有多个构造器,所以Spring得根据参数个数、类型确定需要调用的构造器
// 在使用构造器创建实例后,Spring会将解析过后确定下来的构造器或工厂方法保存在缓存中,避免再次创建相同bean时再次解析
// 标识构造函数和工厂方法是否已经被解析过
boolean resolved = false;
// 是否需要自动注入
boolean autowireNecessary = false;
// 如果有参数,那么创建的对象肯定不一样,就不能用缓存了
if (args == null) {
synchronized (mbd.constructorArgumentLock) {
// 因为一个类可能由多个构造函数,所以需要根据配置文件中配置的参数或传入的参数来确定最终调用的构造函数。
// 因为判断过程会比较,所以spring会将解析、确定好的构造函数缓存到BeanDefinition中的resolvedConstructorOrFactoryMethod字段中
// 在下次创建相同时直接从RootBeanDefinition中的属性resolvedConstructorOrFactoryMethod缓存的值获取,避免再次解析
if (mbd.resolvedConstructorOrFactoryMethod != null) {
resolved = true;
autowireNecessary = mbd.constructorArgumentsResolved;
}
}
}
// 如果已经解析过,则使用resolvedConstructorOrFactoryMethod缓存里解析好的构造函数方法
if (resolved) {
if (autowireNecessary) {
// 有参构造函数自动注入
return autowireConstructor(beanName, mbd, null, null);
}
else {
// 使用默认的无参构造
return instantiateBean(beanName, mbd);
}
}
// 应用后置处理器SmartInstantiationAwareBeanPostProcessor,拿到bean的候选构造函数
// 一般就是二种情况: 1) 只有一个有参构造方法 2) 有且仅有@Autowired注解构造
Constructor<?>[] ctors = determineConstructorsFromBeanPostProcessors(beanClass, beanName);
// 以下情况符合其一即可进入
// 1、存在可选构造方法
// 2、自动装配模型为构造函数自动装配
// 3、给BeanDefinition中设置了构造参数值
// 4、有参与构造函数参数列表的参数
if (ctors != null || mbd.getResolvedAutowireMode() == AUTOWIRE_CONSTRUCTOR ||
mbd.hasConstructorArgumentValues() || !ObjectUtils.isEmpty(args)) {
// 通过有参构造方法初始化bean
return autowireConstructor(beanName, mbd, ctors, args);
}
// 找出最合适的默认构造方法
ctors = mbd.getPreferredConstructors();
if (ctors != null) {
// 构造函数自动注入
return autowireConstructor(beanName, mbd, ctors, null);
}
// 没有特殊处理,则使用默认的构造函数进行bean的实例化
return instantiateBean(beanName, mbd);
}
Supplier
接口实例,则使用Supplier接口回调来实例化@FunctionalInterface
public interface Supplier<T> {
T get();
}
factory-method
,则该方法必须为静态方法,可以直接调用静态方法创建对象,否则抛出异常,这就是静态工厂模式
factory-method + factory-bean
,则代表该方法为普通方法,则,这就是实例工厂模式
@Component
public class Person {
private Animal animal;
@Autowired
public Person(Animal animal) {
this.animal = animal;
}
...
}
或者
@Component
public class Person {
private Animal animal;
public Person(Animal animal) {
this.animal = animal;
}
...
}
@Autowired
,代表参数可以从Bean容器中依赖注入只有一个
时,@Autowired注解可以省略,默认
从bean容器注入需要的参数RootBeanDefinition
中获取Class对象clazz.getDeclaredConstructor()
ctor.newInstance()
protected void applyMergedBeanDefinitionPostProcessors(RootBeanDefinition mbd, Class<?> beanType, String beanName) {
//获取BeanFactory中已注册的BeanPostProcessor
for (BeanPostProcessor bp : getBeanPostProcessors()) {
if (bp instanceof MergedBeanDefinitionPostProcessor) {
// 调用MergedBeanDefinitionPostProcessor的postProcessMergedBeanDefinition方法,
// 对指定bean的给定MergedBeanDefinition进行后置处理,@Autowire @Resource注解在这边对元数据进行预解析
MergedBeanDefinitionPostProcessor bdp = (MergedBeanDefinitionPostProcessor) bp;
bdp.postProcessMergedBeanDefinition(mbd, beanType, beanName);
}
}
}
实例化后
的操作(修改bean定义)@PostConstruct
@PreDestroy
方法和 @Resource
属性缓存起来,供以后调用@Autowired
@Value
属性并缓存起来,供以后调用ObjectFactory
的形式加入到三级缓存protected void addSingletonFactory(String beanName, ObjectFactory<?> singletonFactory) {
Assert.notNull(singletonFactory, "Singleton factory must not be null");
synchronized (this.singletonObjects) {
// 如果beanName不存在于一级缓存(完整对象bean)
if (!this.singletonObjects.containsKey(beanName)) {
// 将beanName和singletonFactory
// 注册到三级缓存(工厂bean缓存)
this.singletonFactories.put(beanName, singletonFactory);
// 移除二级缓存(没有属性填充bean)
this.earlySingletonObjects.remove(beanName);
// 将beanName注册到registeredSingletons缓存(已经注册的单例集合)
this.registeredSingletons.add(beanName);
}
}
}
getEarlyBeanReference();
创建bean的对象工厂
,添加到三级缓存
中而已ObjectFactory.getObject()
方法的时候,就会回调getEarlyBeanReference(beanName, mbd, bean)
方法,获取到提前暴露的bean
的早期引用,从而解决循环依赖// 获取早期访问指定bean的引用,通常用于解析循环引用
protected Object getEarlyBeanReference(String beanName, RootBeanDefinition mbd, Object bean) {
Object exposedObject = bean;
// 如果bean不为空 && mbd不是合成 && 存在InstantiationAwareBeanPostProcessors
if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
for (BeanPostProcessor bp : getBeanPostProcessors()) {
// 应用所有SmartInstantiationAwareBeanPostProcessor,调用getEarlyBeanReference方法
if (bp instanceof SmartInstantiationAwareBeanPostProcessor) {
// 允许SmartInstantiationAwareBeanPostProcessor返回指定bean的早期引用
SmartInstantiationAwareBeanPostProcessor ibp = (SmartInstantiationAwareBeanPostProcessor) bp;
exposedObject = ibp.getEarlyBeanReference(exposedObject, beanName);
}
}
}
// 如果不存在SmartInstantiationAwareBeanPostProcessor,则直接返回原始的bean对象
return exposedObject;
}
属性填充
,对bean各个属性值进行注入,可能存在依赖于其它bean的属性,则会递归初始依赖的beanprotected void populateBean(String beanName, RootBeanDefinition mbd, @Nullable BeanWrapper bw) {
// 一般正常注入都是有值的
if (bw == null) {
// 如果BeanWrapper为空,但是有属性值,就跑异常
if (mbd.hasPropertyValues()) {
throw new BeanCreationException(
mbd.getResourceDescription(), beanName, "Cannot apply property values to null instance");
}
else {
// 没有可填充的属性
return;
}
}
// 给InstantiationAwareBeanPostProcessors最后一次机会在属性注入前修改Bean的属性值
// 具体通过调用postProcessAfterInstantiation方法,如果调用返回false,表示不必继续进行依赖注入,直接返回
if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
for (InstantiationAwareBeanPostProcessor bp : getBeanPostProcessorCache().instantiationAware) {
if (!bp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) {
return;
}
}
}
// 获取到bean定义中封装好的属性值
PropertyValues pvs = (mbd.hasPropertyValues() ? mbd.getPropertyValues() : null);
// 自动注入:包括名称注入和类型注入(不推荐使用,只支持 XML 配置方式)
int resolvedAutowireMode = mbd.getResolvedAutowireMode();
if (resolvedAutowireMode == AUTOWIRE_BY_NAME || resolvedAutowireMode == AUTOWIRE_BY_TYPE) {
// 1)把需要注入的属性先拷贝过来 2)经过下面的方法,获取到需要注入的bean,也会存到这里面来
// 简单点说,就是这里面存储了哪些属性需要注入,然后下面获取到也存到这里面来, 但此时还没有进行引用关系的绑定
MutablePropertyValues newPvs = new MutablePropertyValues(pvs);
// 根据名称注入
if (resolvedAutowireMode == AUTOWIRE_BY_NAME) {
autowireByName(beanName, mbd, bw, newPvs);
}
// 根据类型注入
if (resolvedAutowireMode == AUTOWIRE_BY_TYPE) {
autowireByType(beanName, mbd, bw, newPvs);
}
pvs = newPvs;
}
// 容器是否注册了InstantiationAwareBeanPostProcessor
boolean hasInstAwareBpps = hasInstantiationAwareBeanPostProcessors();
// 是否需要依赖检查
boolean needsDepCheck = (mbd.getDependencyCheck() != AbstractBeanDefinition.DEPENDENCY_CHECK_NONE);
// 注解注入
PropertyDescriptor[] filteredPds = null;
if (hasInstAwareBpps) {
if (pvs == null) {
pvs = mbd.getPropertyValues();
}
for (InstantiationAwareBeanPostProcessor bp : getBeanPostProcessorCache().instantiationAware) {
// 现在最常用的@Autowire属性注入就是这边注入依赖的bean实例对象
// CommonAnnotationBeanPostProcessor.postProcessProperties
// AutowiredAnnotationBeanPostProcessor.postProcessProperties
PropertyValues pvsToUse = bp.postProcessProperties(pvs, bw.getWrappedInstance(), beanName);
if (pvsToUse == null) {
if (filteredPds == null) {
filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
}
pvsToUse = bp.postProcessPropertyValues(pvs, filteredPds, bw.getWrappedInstance(), beanName);
if (pvsToUse == null) {
return;
}
}
pvs = pvsToUse;
}
}
// 依赖检查,循环依赖
if (needsDepCheck) {
if (filteredPds == null) {
filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
}
// 依赖检查,对应depends-on属性
checkDependencies(beanName, mbd, filteredPds, pvs);
}
// 将所有PropertyValues中的属性填充到bean中
if (pvs != null) {
applyPropertyValues(beanName, mbd, bw, pvs);
}
}
总结
实例化后
的操作
set方法存在
) && 非简单属性(包装类
+Number+Date) 的属性名autowireByName()
,通过名称,将需要注入的属性添加到MutablePropertyValues中autowireByType()
,通过类型,将需要注入的属性添加到MutablePropertyValues中applyPropertyValues()
,将添加到MutablePropertyValues中的属性赋值到bean中@Resource
@PostConstruct
@PreDestroy
注解的处理@Autowired
@Value
注解的处理暴力反射访问私有权限
直接赋值初始化Bean
,执行aware接口、执行init-method方法、BeanPostProcessor后置增强等等protected Object initializeBean(final String beanName, final Object bean, @Nullable RootBeanDefinition mbd) {
// 执行Aware方法,如BeanNameAware、BeanClassLoaderAware、BeanFactoryAware
if (System.getSecurityManager() != null) {
AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
invokeAwareMethods(beanName, bean);
return null;
}, getAccessControlContext());
}
else {
invokeAwareMethods(beanName, bean);
}
Object wrappedBean = bean;
if (mbd == null || !mbd.isSynthetic()) {
// 在初始化前应用BeanPostProcessor的postProcessBeforeInitialization方法,允许对bean实例进行包装
wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
}
try {
// 执行初始化方法,包括InitializingBean的afterPropertiesSet()方法、自定义的初始化方法init-method
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方法,允许对bean实例进行包装
wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
}
return wrappedBean;
}
private void invokeAwareMethods(final String beanName, final Object bean) {
if (bean instanceof Aware) {
// BeanNameAware: 实现此接口的类想要拿到beanName,因此我们在这边赋值给它
if (bean instanceof BeanNameAware) {
((BeanNameAware) bean).setBeanName(beanName);
}
// BeanClassLoaderAware:实现此接口的类想要拿到beanClassLoader,因此我们在这边赋值给它
if (bean instanceof BeanClassLoaderAware) {
((BeanClassLoaderAware) bean).setBeanClassLoader(getBeanClassLoader());
}
// BeanFactoryAware: 实现此接口的类想要拿到 BeanFactory,因此我们在这边赋值给它
if (bean instanceof BeanFactoryAware) {
((BeanFactoryAware) bean).setBeanFactory(AbstractAutowireCapableBeanFactory.this);
}
}
}
BeanNameAware
接口、BeanClassLoaderAware
接口、BeanFactoryAware
setxxxAware方法
中拿到对应需要的属性,如:bean名称、bean容器@Override
public Object applyBeanPostProcessorsBeforeInitialization(Object existingBean, String beanName)
throws BeansException {
Object result = existingBean;
// 1.遍历所有注册的BeanPostProcessor实现类,调用postProcessBeforeInitialization方法
for (BeanPostProcessor beanProcessor : getBeanPostProcessors()) {
// 2.在bean初始化方法执行前,调用postProcessBeforeInitialization方法
result = beanProcessor.postProcessBeforeInitialization(result, beanName);
if (result == null) {
return result;
}
}
return result;
}
①
ApplicationContextAwareProcessor
后置处理器
初始化前
从它setxxx方法获取对应上下文东西②
CommonAnnotationBeanPostProcessor
后置处理器解析出的@PostConstruct的执行
InitializingBean接口
,如果是的话则需要调用 afterPropertiesSet方法
(初始化方法)initMethod自定义方法
调用protected void invokeInitMethods(String beanName, final Object bean, RootBeanDefinition mbd)
throws Throwable {
// 1.首先检查bean是否实现了InitializingBean接口,如果是的话调用afterPropertiesSet方法
boolean isInitializingBean = (bean instanceof InitializingBean);
if (isInitializingBean && (mbd == null || !mbd.isExternallyManagedInitMethod("afterPropertiesSet"))) {
if (logger.isDebugEnabled()) {
logger.debug("Invoking afterPropertiesSet() on bean with name '" + beanName + "'");
}
// 2.调用afterPropertiesSet方法
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) {
// 从RootBeanDefinition 中获取initMethod 方法名称
String initMethodName = mbd.getInitMethodName();
if (initMethodName != null && !(isInitializingBean && "afterPropertiesSet".equals(initMethodName)) &&
!mbd.isExternallyManagedInitMethod(initMethodName)) {
// 3.调用自定义初始化方法
invokeCustomInitMethod(beanName, bean, mbd);
}
}
}
@Override
public Object applyBeanPostProcessorsAfterInitialization(Object existingBean, String beanName)
throws BeansException {
Object result = existingBean;
// 1.遍历所有注册的BeanPostProcessor实现类,调用postProcessAfterInitialization方法
for (BeanPostProcessor beanProcessor : getBeanPostProcessors()) {
// 2.在bean初始化方法执行后,调用postProcessAfterInitialization方法
result = beanProcessor.postProcessAfterInitialization(result, beanName);
if (result == null) {
return result;
}
}
return result;
}
注册销毁方法
,DestructionAwareBeanPostProcessor、DisposableBean 接口、自定义销毁方法protected void registerDisposableBeanIfNecessary(String beanName, Object bean, RootBeanDefinition mbd) {
AccessControlContext acc = (System.getSecurityManager() != null ? getAccessControlContext() : null);
if (!mbd.isPrototype() && requiresDestruction(bean, mbd)) {
if (mbd.isSingleton()) {
// 注册一个 DisposableBean 实现,该实现为给定 Bean 执行所有销毁工作:DestructionAwareBeanPostProcessor、DisposableBean 接口、自定义销毁方法
// Register a DisposableBean implementation that performs all destruction
// work for the given bean: DestructionAwareBeanPostProcessors,
// DisposableBean interface, custom destroy method.
registerDisposableBean(beanName, new DisposableBeanAdapter(
bean, beanName, mbd, getBeanPostProcessorCache().destructionAware, acc));
}
else {
// A bean with a custom scope...
Scope scope = this.scopes.get(mbd.getScope());
if (scope == null) {
throw new IllegalStateException("No Scope registered for scope name '" + mbd.getScope() + "'");
}
scope.registerDestructionCallback(beanName, new DisposableBeanAdapter(
bean, beanName, mbd, getBeanPostProcessorCache().destructionAware, acc));
}
}
}