当我们 beanDefinitionReader.loadBeanDefinitions(resource);将读取的资源放defaultListableBeanFactory工厂当中此时只是将数据缓存到工厂的成员变量此时Spring.xml文件的bean还没有被实例化。
当我们真正去向工厂索要例如实例“student”的实例对象时才会被创建典型的工厂模式。
//读取完我们需要哪个对象找工厂要
Student student = (Student) defaultListableBeanFactory.getBean("student");
Spring中命名很规范一般do开头都是真正内部解析的方法
该方法返回一个bean实例 protected 类型仅供内部调用
/**
* 返回指定bean的一个实例,该实例可以是共享的,也可以是独立的。
* @param 要检索的bean的名称
* @param requiredType要检索的bean的必需类型(class二进制名)
* @param args jvm参数
* 仅在创建新实例而不是检索现有实例时应用
* @param typeCheckOnly 是否获取实例进行类型检查,
* not for actual use
* @return an instance of the bean
* @throws BeansException if the bean could not be created
*/
@SuppressWarnings("unchecked")
protected <T> T doGetBean(
String name, @Nullable Class<T> requiredType, @Nullable Object[] args, boolean typeCheckOnly)
throws BeansException {
//将名字转换成标准的名字去掉一些符号前缀啥的
String beanName = transformedBeanName(name);
Object bean;
// Eagerly check singleton cache for manually registered singletons.
/*在缓存中查找是否有对应的实例bean 有返回对应单例bean 只有单例才能共享
极大了提高效率
第一次访问为null 直接进入else
*/
Object sharedInstance = getSingleton(beanName);
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 + "'");
}
}
//如果缓存存在bean直接返回
bean = getObjectForBeanInstance(sharedInstance, name, beanName, null);
}
else {
// Fail if we're already creating this bean instance:
// We're assumably within a circular reference.
//防止多线程去创建该bean
if (isPrototypeCurrentlyInCreation(beanName)) {
throw new BeanCurrentlyInCreationException(beanName);
}
// Check if bean definition exists in this factory.
/**
此时会检查该bean定义是否在工厂存在 也就是说在
工厂的concurrentHashMap中存在才能在这个工厂读取bean的信息
才能被实例化
**/
BeanFactory parentBeanFactory = getParentBeanFactory();
if (parentBeanFactory != null && !containsBeanDefinition(beanName)) {
// Not found -> check parent.
String nameToLookup = originalBeanName(name);
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);
}
}
if (!typeCheckOnly) {
//标记当前bean 已经创建完或者是正在进行创建防止出现重复创建
markBeanAsCreated(beanName);
}
try {
/*
RootBeanDefinition bean定义的基类里面存储当前了BeanDefinition的所有信息
包括一些属性和状态 可以理解为将里面的一些属性进行更详细的包装 最终的表示形态
*/
RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
//双重检测判断合并后的beanDefinition是否时抽象的(抽象的不能被实例化)
checkMergedBeanDefinition(mbd, beanName, args);
// Guarantee initialization of beans that the current bean depends on.
/*
检测一些依赖关系 A依赖B B也得创建出来 这里是得到
依赖bean的 className数组
*/
String[] dependsOn = mbd.getDependsOn();
//对依赖的bean进行处理
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的注册解析
registerDependentBean(dep, beanName);
try {
//重复之前的的获取方法 类似getBean("student) 递归操作
getBean(dep);
}
catch (NoSuchBeanDefinitionException ex) {
throw new BeanCreationException(mbd.getResourceDescription(), beanName,
"'" + beanName + "' depends on missing bean '" + dep + "'", ex);
}
}
}
// Create bean instance.
//创建bean实例
//判断bean的作用域 是否为Singleton
if (mbd.isSingleton()) {
//得到单例的bean实例创建成功
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.
destroySingleton(beanName);
throw ex;
}
});
//返回客户端想要的实例bean 底层进行了判端是什么方式创建的bean
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());
}
}
//获取到指定的bean实例
return (T) bean;
}
@Override
@Nullable
public Object getSingleton(String beanName) {
return getSingleton(beanName, true);
}
/**
* 返回以给定名称注册的(原始)单例对象。
* 检查已经实例化的singleton,并允许早期引用当前创建的singleton(解析循环引用)。
* 返回以给定名称注册的(原始)单例对象。 如果缓存有 直接返回
* @param beanName 要查找的bean的名称
* @param allowearleference是否应创建早期引用
* @return 已注册的单例对象,或{@code null}(如果找不到)
*/
@Nullable
protected Object getSingleton(String beanName, boolean allowEarlyReference) {
/*
在当前的concurrentHashMap当中查找key为beanName 的value值
改singletonObjects 缓存bean工厂所有的单例bean
*/
Object singletonObject = this.singletonObjects.get(beanName);
//是否为null ||当前bean是否正在创建
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;
}
该singleton缓存所有的单例bean,当我们通过工厂获取单例bean时如果有缓存都是从这个concurrentHashmap当中拿到对应的bean对象
/**
*将指定的bean标记为已创建(或即将创建)。
*这允许bean工厂优化其缓存,以便重复创建指定的bean。
* creation of the specified bean.
* @param beanName the name of the bean
*/
protected void markBeanAsCreated(String beanName) {
//底层缓存key的set集合当中是否有当前的key
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. //标记当前的bean处于创建和即将创建状态 提高并发效率
clearMergedBeanDefinition(beanName);
//将其加到set集合当中
this.alreadyCreated.add(beanName);
}
}
}
}
重载方法
/**
* 返回以给定名称注册的(raw)singleton对象,
* 创建并注册一个新的,如果还没有注册。
* @param beanName bean的名字
* @param singletonFactory 延迟创建单例的ObjectFactory
* with, if necessary
* @return the registered singleton object
*/
public Object getSingleton(String beanName, ObjectFactory<?> singletonFactory) {
Assert.notNull(beanName, "Bean name must not be null");
//创建单例bean 该方法操作时只能串行
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 {
//执行lambda表达式函数式接口方法 也就是真正的创建实例方法
//此时返回的实例就是创建好的实例
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) {
//实例如果获取到了
//此时添加缓存到ConcurrentHashMap当中
addSingleton(beanName, singletonObject);
}
}
return singletonObject;
}
}
将其加入到缓存当中当时删除一些预缓存和对应使用的工厂缓存同时赋值已创建实例的set集合(之前set 过了 因为是set集合所有会覆盖)
//---------------------------------------------------------------------
// Implementation of relevant AbstractBeanFactory template methods
// 相关AbstractBeanFactory模板方法的实现
//---------------------------------------------------------------------
/**
* 这个类的中心方法:创建一个bean实例,填充bean实例,应用后处理程序,等等。
* @see #doCreateBean
*/
@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.
//拿到beanName 的class 对象 准备实例化
Class<?> resolvedClass = resolveBeanClass(mbd, beanName);
if (resolvedClass != null && !mbd.hasBeanClass() && mbd.getBeanClassName() != null) {
//如果Class对象拿到将其重新封装到RootBeanDefinition当中
mbdToUse = new RootBeanDefinition(mbd);
mbdToUse.setBeanClass(resolvedClass);
}
// Prepare method overrides.
try {
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.
//spring前置处理器的一些处理 如果我们定义了前置处理器会进行相关处理
Object bean = resolveBeforeInstantiation(beanName, mbdToUse);
if (bean != null) {
//如果没有定义 返回ben
return bean;
}
}
catch (Throwable ex) {
throw new BeanCreationException(mbdToUse.getResourceDescription(), beanName,
"BeanPostProcessor before instantiation of bean failed", ex);
}
try {
//此时开始真正的创建bean实例的逻辑 当前方法只是获取class对象和一些预加载处理操作
//此时返回的就是已经实例化的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);
}
}
/**
* Actually create the specified bean. Pre-creation processing has already happened
* at this point, e.g. checking {@code postProcessBeforeInstantiation} callbacks.
* Differentiates between default bean instantiation, use of a
* factory method, and autowiring a constructor.
* @param beanName the name of the bean
* @param mbd the merged bean definition for the bean
* @param args explicit arguments to use for constructor or factory method invocation
* @return a new instance of the bean
* @throws BeanCreationException if the bean could not be created
* @see #instantiateBean
* @see #instantiateUsingFactoryMethod
* @see #autowireConstructor
*/
protected Object doCreateBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)
throws BeanCreationException {
// Instantiate the bean.
//bean包装器 将bean添加些描述参数信息 封装到wrepper当中 方便于管理
BeanWrapper instanceWrapper = null;
if (mbd.isSingleton()) {
/*将正在创建的实例标识去掉前面
前面当beanName准备要创建对象时会将要创建的beanName放到缓存当中
表示要开始真正的创建
*/
instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);
}
if (instanceWrapper == null) {
//如果包装器为空 将其bean实例进行包装 此时bean已被实例化
//内部会调用simple 构造方法去实例化对象 此时属性并未赋值
instanceWrapper = createBeanInstance(beanName, mbd, args);
}
//获取被包装的实例化对象 如Student@1709
Object bean = instanceWrapper.getWrappedInstance();
//获取bean的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 {
//处理应用处理器后置的一些操作
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.
//尽早的缓存单例以能够解析循环引用
//即使是由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");
}
//添加一个单例的工厂实例
addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean));
}
// 定义初始化bean实例。
Object exposedObject = bean;
try {
/*使用bean定义中的属性值填充给定BeanWrapper中的bean实例。
传入wrapper和rootBeanDefinition中存放着 wrapperzhong 中bean实例的属性
通过beanName将属性填充
*/
populateBean(beanName, mbd, instanceWrapper);
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);
}
}
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);
}
//返回初始化完成的bean
return exposedObject;
}
/**
* 使用适当的实例化策略为指定的bean创建一个新实例 当未指定采用简单实例化
* factory method工厂方法, constructor autowiring、构造函数自动连接, or simple 简单实例化。instantiation.
*/
protected BeanWrapper createBeanInstance(String beanName, RootBeanDefinition mbd, @Nullable Object[] args) {
// Make sure bean class is actually resolved at this point.
Class<?> beanClass = resolveBeanClass(mbd, beanName);
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<?> instanceSupplier = mbd.getInstanceSupplier();
if (instanceSupplier != null) {
return obtainFromSupplier(instanceSupplier, beanName);
}
if (mbd.getFactoryMethodName() != null) {
return instantiateUsingFactoryMethod(beanName, mbd, args);
}
// Shortcut when re-creating the same bean...
boolean resolved = false;
boolean autowireNecessary = false;
if (args == null) {
synchronized (mbd.constructorArgumentLock) {
if (mbd.resolvedConstructorOrFactoryMethod != null) {
resolved = true;
autowireNecessary = mbd.constructorArgumentsResolved;
}
}
}
if (resolved) {
if (autowireNecessary) {
return autowireConstructor(beanName, mbd, null, null);
}
else {
return instantiateBean(beanName, mbd);
}
}
// Candidate constructors for autowiring?
//选取特定的构造器是创建实例
Constructor<?>[] ctors = determineConstructorsFromBeanPostProcessors(beanClass, beanName);
if (ctors != null || mbd.getResolvedAutowireMode() == AUTOWIRE_CONSTRUCTOR ||
mbd.hasConstructorArgumentValues() || !ObjectUtils.isEmpty(args)) {
return autowireConstructor(beanName, mbd, ctors, args);
}
// Preferred constructors for default construction?
//是否使用默认的构造器
ctors = mbd.getPreferredConstructors();
if (ctors != null) {
return autowireConstructor(beanName, mbd, ctors, null);
}
// No special handling: simply use no-arg constructor.
//没有特殊情况 就使用简单的构造器进行创建对象 mbd描述整个bean定义信息和操作信息
return instantiateBean(beanName, mbd);
}
/**
* 使用默认构造函数实例化给定的bean。
*/
protected BeanWrapper instantiateBean(String beanName, RootBeanDefinition mbd) {
try {
Object beanInstance;
if (System.getSecurityManager() != null) {
//安全检查
beanInstance = AccessController.doPrivileged(
(PrivilegedAction<Object>) () -> getInstantiationStrategy().instantiate(mbd, beanName, this),
getAccessControlContext());
}
else {
//使用beanDefinition特定的策略去创建实例
beanInstance = getInstantiationStrategy().instantiate(mbd, beanName, this);
}
BeanWrapper bw = new BeanWrapperImpl(beanInstance);
//包装bean对象
initBeanWrapper(bw);
return bw;
}
catch (Throwable ex) {
throw new BeanCreationException(
mbd.getResourceDescription(), beanName, "Instantiation of bean failed", ex);
}
}
@Override
public Object instantiate(RootBeanDefinition bd, @Nullable String beanName, BeanFactory owner) {
// 如果没有重写,没有用CGLIB重写类。
if (!bd.hasMethodOverrides()) {
Constructor<?> constructorToUse;
//锁同步
synchronized (bd.constructorArgumentLock) {
constructorToUse = (Constructor<?>) bd.resolvedConstructorOrFactoryMethod;
if (constructorToUse == null) {
final Class<?> clazz = bd.getBeanClass();
//获取Class对象是否为接口 接口不能实例抛异常
if (clazz.isInterface()) {
throw new BeanInstantiationException(clazz, "Specified class is an interface");
}
try {
if (System.getSecurityManager() != null) {
constructorToUse = AccessController.doPrivileged(
(PrivilegedExceptionAction<Constructor<?>>) clazz::getDeclaredConstructor);
}
else {
//获取对应的构造方法
constructorToUse = clazz.getDeclaredConstructor();
}
bd.resolvedConstructorOrFactoryMethod = constructorToUse;
}
catch (Throwable ex) {
throw new BeanInstantiationException(clazz, "No default constructor found", ex);
}
}
}
//通过构造方法实例化对象 此时我们beanName对应的Class生成对象
// 返回 一般xml文件都是走构造方法生成对象
return BeanUtils.instantiateClass(constructorToUse);
}
else {
//如果使用了CGLIB动态代理来生成实例
// Must generate CGLIB subclass.
return instantiateWithMethodInjection(bd, beanName, owner);
}
}
/**
* 如有必要,添加给定的singleton工厂以生成指定的singleton。
* 被要求尽早地注册单例,例如能够解析循环引用。
* @param beanName the name of the bean
* @param singletonFactory the factory for the singleton object
*/
protected void addSingletonFactory(String beanName, ObjectFactory<?> singletonFactory) {
Assert.notNull(singletonFactory, "Singleton factory must not be null");
synchronized (this.singletonObjects) {
//判断缓存是否有改单例bean
if (!this.singletonObjects.containsKey(beanName)) {
//缓存beanName指定的工厂到hashMap当中
this.singletonFactories.put(beanName, singletonFactory);
//删除之前的beanName对应的实例对象 显然第一创建没有
this.earlySingletonObjects.remove(beanName);
//将该beanName已注册的se集合当中
this.registeredSingletons.add(beanName);
}
}
}
try {
//获取到对应bean实例
singletonObject = singletonFactory.getObject();
//表示bean实例已经创建完成
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) {
//此时将bean 加入缓存 beanname做key,instance做value
addSingleton(beanName, singletonObject);
}
}
return singletonObject;
}
/**
* Add the given singleton object to the singleton cache of this factory.
* To be called for eager registration of singletons.
* @param beanName the name of the bean
* @param singletonObject the singleton object
*/
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);
}
}