Spring源码学习bean的加载

Posted VVII

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Spring源码学习bean的加载相关的知识,希望对你有一定的参考价值。

加油加油 ?? 

 

bean加载的大致过程

  1     /**
  2      * Return an instance, which may be shared or independent, of the specified bean.
  3      *
  4      * @param name          the name of the bean to retrieve
  5      * @param requiredType  the required type of the bean to retrieve
  6      * @param args          arguments to use when creating a bean instance using explicit arguments
  7      *                      (only applied when creating a new instance as opposed to retrieving an existing one)
  8      * @param typeCheckOnly whether the instance is obtained for a type check,
  9      *                      not for actual use
 10      * @return an instance of the bean
 11      * @throws BeansException if the bean could not be created
 12      */
 13     @SuppressWarnings("unchecked")
 14     protected <T> T doGetBean(final String name, @Nullable final Class<T> requiredType,
 15                               @Nullable final Object[] args, boolean typeCheckOnly) throws BeansException {
 16         //转换对应的beanName
 17         final String beanName = transformedBeanName(name);
 18         Object bean;
 19 
 20         // 尝试从缓存中加载单例
 21         // Eagerly check singleton cache for manually registered singletons.
 22         Object sharedInstance = getSingleton(beanName);
 23         if (sharedInstance != null && args == null) {
 24             if (logger.isTraceEnabled()) {
 25                 if (isSingletonCurrentlyInCreation(beanName)) {
 26                     logger.trace("Returning eagerly cached instance of singleton bean ‘" + beanName +
 27                             "‘ that is not fully initialized yet - a consequence of a circular reference");
 28                 } else {
 29                     logger.trace("Returning cached instance of singleton bean ‘" + beanName + "‘");
 30                 }
 31             }
 32             //bean实例化
 33             bean = getObjectForBeanInstance(sharedInstance, name, beanName, null);
 34         } else {
 35             // 原型模式依赖检查
 36             // Fail if we‘re already creating this bean instance:
 37             // We‘re assumably within a circular reference.
 38             if (isPrototypeCurrentlyInCreation(beanName)) {
 39                 throw new BeanCurrentlyInCreationException(beanName);
 40             }
 41 
 42             // Check if bean definition exists in this factory.
 43             BeanFactory parentBeanFactory = getParentBeanFactory();
 44             // 检测parentBeanFactory
 45             if (parentBeanFactory != null && !containsBeanDefinition(beanName)) {
 46                 // Not found -> check parent.
 47                 String nameToLookup = originalBeanName(name);
 48                 if (parentBeanFactory instanceof AbstractBeanFactory) {
 49                     return ((AbstractBeanFactory) parentBeanFactory).doGetBean(
 50                             nameToLookup, requiredType, args, typeCheckOnly);
 51                 } else if (args != null) {
 52                     // Delegation to parent with explicit args.
 53                     return (T) parentBeanFactory.getBean(nameToLookup, args);
 54                 } else if (requiredType != null) {
 55                     // No args -> delegate to standard getBean method.
 56                     return parentBeanFactory.getBean(nameToLookup, requiredType);
 57                 } else {
 58                     return (T) parentBeanFactory.getBean(nameToLookup);
 59                 }
 60             }
 61 
 62             if (!typeCheckOnly) {
 63                 markBeanAsCreated(beanName);
 64             }
 65 
 66             try {
 67                 final RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
 68                 checkMergedBeanDefinition(mbd, beanName, args);
 69 
 70                 // Guarantee initialization of beans that the current bean depends on.
 71                 String[] dependsOn = mbd.getDependsOn();
 72                 // 寻找依赖
 73                 if (dependsOn != null) {
 74                     for (String dep : dependsOn) {
 75                         if (isDependent(beanName, dep)) {
 76                             throw new BeanCreationException(mbd.getResourceDescription(), beanName,
 77                                     "Circular depends-on relationship between ‘" + beanName + "‘ and ‘" + dep + "‘");
 78                         }
 79                         registerDependentBean(dep, beanName);
 80                         try {
 81                             getBean(dep);
 82                         } catch (NoSuchBeanDefinitionException ex) {
 83                             throw new BeanCreationException(mbd.getResourceDescription(), beanName,
 84                                     "‘" + beanName + "‘ depends on missing bean ‘" + dep + "‘", ex);
 85                         }
 86                     }
 87                 }
 88 
 89                 // 根据不同Scope创建bean
 90                 // Create bean instance.
 91                 if (mbd.isSingleton()) {
 92                     sharedInstance = getSingleton(beanName, () -> {
 93                         try {
 94                             return createBean(beanName, mbd, args);
 95                         } catch (BeansException ex) {
 96                             // Explicitly remove instance from singleton cache: It might have been put there
 97                             // eagerly by the creation process, to allow for circular reference resolution.
 98                             // Also remove any beans that received a temporary reference to the bean.
 99                             destroySingleton(beanName);
100                             throw ex;
101                         }
102                     });
103                     bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
104                 } else if (mbd.isPrototype()) {
105                     // It‘s a prototype -> create a new instance.
106                     Object prototypeInstance = null;
107                     try {
108                         beforePrototypeCreation(beanName);
109                         prototypeInstance = createBean(beanName, mbd, args);
110                     } finally {
111                         afterPrototypeCreation(beanName);
112                     }
113                     bean = getObjectForBeanInstance(prototypeInstance, name, beanName, mbd);
114                 } else {
115                     String scopeName = mbd.getScope();
116                     final Scope scope = this.scopes.get(scopeName);
117                     if (scope == null) {
118                         throw new IllegalStateException("No Scope registered for scope name ‘" + scopeName + "‘");
119                     }
120                     try {
121                         Object scopedInstance = scope.get(beanName, () -> {
122                             beforePrototypeCreation(beanName);
123                             try {
124                                 return createBean(beanName, mbd, args);
125                             } finally {
126                                 afterPrototypeCreation(beanName);
127                             }
128                         });
129                         bean = getObjectForBeanInstance(scopedInstance, name, beanName, mbd);
130                     } catch (IllegalStateException ex) {
131                         throw new BeanCreationException(beanName,
132                                 "Scope ‘" + scopeName + "‘ is not active for the current thread; consider " +
133                                         "defining a scoped proxy for this bean if you intend to refer to it from a singleton",
134                                 ex);
135                     }
136                 }
137             } catch (BeansException ex) {
138                 cleanupAfterBeanCreationFailure(beanName);
139                 throw ex;
140             }
141         }
142 
143         // 类型转换
144         // Check if required type matches the type of the actual bean instance.
145         if (requiredType != null && !requiredType.isInstance(bean)) {
146             try {
147                 T convertedBean = getTypeConverter().convertIfNecessary(bean, requiredType);
148                 if (convertedBean == null) {
149                     throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass());
150                 }
151                 return convertedBean;
152             } catch (TypeMismatchException ex) {
153                 if (logger.isTraceEnabled()) {
154                     logger.trace("Failed to convert bean ‘" + name + "‘ to required type ‘" +
155                             ClassUtils.getQualifiedName(requiredType) + "‘", ex);
156                 }
157                 throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass());
158             }
159         }
160         return (T) bean;
161     }

FactoryBean的使用

 1 public interface FactoryBean<T> {
 2 
 3     
 4     // 返回由FactoryBean创建的bean实例,若是单例则会将该实例放入Spring容器中单例缓存池中
 5     @Nullable
 6     T getObject() throws Exception;
 7 
 8     // 返回beanFactory创建的bean类型
 9     @Nullable
10     Class<?> getObjectType();
11 
12     
13     // 返回beanFactory创建的bean实例的作用域是Singleton还是Prototype
14     default boolean isSingleton() {
15         return true;
16     }
17 
18 }

(一)获取对应的beanName

技术图片
 1     protected String transformedBeanName(String name) {
 2         return canonicalName(BeanFactoryUtils.transformedBeanName(name));
 3     }
 4 
 5 
 6 
 7 
 8     // 去掉前缀&
 9     public static String transformedBeanName(String name) {
10         Assert.notNull(name, "‘name‘ must not be null");
11         if (!name.startsWith(BeanFactory.FACTORY_BEAN_PREFIX)) {
12             return name;
13         }
14         return transformedBeanNameCache.computeIfAbsent(name, beanName -> {
15             do {
16                 beanName = beanName.substring(BeanFactory.FACTORY_BEAN_PREFIX.length());
17             }
18             while (beanName.startsWith(BeanFactory.FACTORY_BEAN_PREFIX));
19             return beanName;
20         });
21     }
22 
23 
24 
25    //取指定alias所表示的最终beanName,eg:若别名A指向B的bean则返回bean;若别 
26    //名A指向别名B,别名B指向名称为C的Bean,则返回C
27 public String canonicalName(String name) {
28    String canonicalName = name;
29    // Handle aliasing...
30    String resolvedName;
31    do {
32       resolvedName = this.aliasMap.get(canonicalName);
33       if (resolvedName != null) {
34          canonicalName = resolvedName;
35       }
36    }
37    while (resolvedName != null);
38    return canonicalName;
39 }
获取对应的beanName

(二)尝试从缓存中加载单例

技术图片
 1     @Nullable
 2     protected Object getSingleton(String beanName, boolean allowEarlyReference) {
 3         // 缓存中获取(beanName,bean Instance)
 4         Object singletonObject = this.singletonObjects.get(beanName);
 5         // 缓存中没有 且 正在创建中
 6         if (singletonObject == null && isSingletonCurrentlyInCreation(beanName)) {
 7             // 全局同步
 8             synchronized (this.singletonObjects) {
 9                 // 是否正在加载该bean
10                 singletonObject = this.earlySingletonObjects.get(beanName);
11                 // 没有加载,且允许早期依赖则进行处理
12                 if (singletonObject == null && allowEarlyReference) {
13                     // 获取对应的ObjectFactory
14                     ObjectFactory<?> singletonFactory = this.singletonFactories.get(beanName);
15                     //earlySingletonObjects (beanName,bean Instance),与singletonObject区别是当一个单例bean放入之中,
16                     // bean还在创建过程中,即可使用getBean方法获取到,其目的是检测循环引用
17                     // singletonFactories  (beanName,ObjectFactory)
18                     if (singletonFactory != null) {
19                         singletonObject = singletonFactory.getObject();
20                         //earlySingletonObjects,singletonFactories 不能同时存在同一个beanName
21                         this.earlySingletonObjects.put(beanName, singletonObject);
22                         this.singletonFactories.remove(beanName);
23                     }
24                 }
25             }
26         }
27         return singletonObject;
28     }
getSingleton

(1)先从缓存singletonObjects中获取实例

(2)未获取到且正在创建中,则从earySingletonObjects获取

(3)没有加载且允许早期依赖则获取对应的ObjectFactory

(4)对应的ObjectFactory不为空则调用其getObject()方法,创建实例,并将实例加如earlySingletonObjects,且将singletonFactories中的ObjectFactory移除

(三)bean实例化

技术图片
 1     protected Object getObjectForBeanInstance(
 2             Object beanInstance, String name, String beanName, @Nullable RootBeanDefinition mbd) {
 3 
 4         // Don‘t let calling code try to dereference the factory if the bean isn‘t a factory.
 5         // name以&为前缀
 6         if (BeanFactoryUtils.isFactoryDereference(name)) {
 7             if (beanInstance instanceof NullBean) {
 8                 return beanInstance;
 9             }
10             // 不是FactoryBean类型
11             if (!(beanInstance instanceof FactoryBean)) {
12                 throw new BeanIsNotAFactoryException(beanName, beanInstance.getClass());
13             }
14         }
15 
16         // Now we have the bean instance, which may be a normal bean or a FactoryBean.
17         // If it‘s a FactoryBean, we use it to create a bean instance, unless the
18         // caller actually wants a reference to the factory.
19         // 不是FactoryBean类型或不以&为前缀
20         if (!(beanInstance instanceof FactoryBean) || BeanFactoryUtils.isFactoryDereference(name)) {
21             return beanInstance;
22         }
23 
24         Object object = null;
25         if (mbd == null) {
26             // 从缓存中加载bean
27             object = getCachedObjectForFactoryBean(beanName);
28         }
29         if (object == null) {
30             // Return bean instance from factory.
31             FactoryBean<?> factory = (FactoryBean<?>) beanInstance;
32             // Caches object obtained from FactoryBean if it is a singleton.
33             if (mbd == null && containsBeanDefinition(beanName)) {
34                 // 将存储XML配置文件的GenericBeanDefinition转化为RootBeanDefinition,
35                 // 如果指定BeanName是子Bean的话 同时合并分类的相关属性
36                 mbd = getMergedLocalBeanDefinition(beanName);
37             }
38             boolean synthetic = (mbd != null && mbd.isSynthetic());
39             object = getObjectFromFactoryBean(factory, beanName, !synthetic);
40         }
41         return object;
42     }
getObjectForBeanInstance
技术图片
 1     protected Object getObjectFromFactoryBean(FactoryBean<?> factory, String beanName, boolean shouldPostProcess) {
 2         // 单例
 3         if (factory.isSingleton() && containsSingleton(beanName)) {
 4             synchronized (getSingletonMutex()) {
 5                 Object object = this.factoryBeanObjectCache.get(beanName);
 6                 if (object == null) {
 7                     object = doGetObjectFromFactoryBean(factory, beanName);
 8                     // Only post-process and store if not put there already during getObject() call above
 9                     // (e.g. because of circular reference processing triggered by custom getBean calls)
10                     Object alreadyThere = this.factoryBeanObjectCache.get(beanName);
11                     if (alreadyThere != null) {
12                         object = alreadyThere;
13                     }
14                     else {
15                         if (shouldPostProcess) {
16                             if (isSingletonCurrentlyInCreation(beanName)) {
17                                 // Temporarily return non-post-processed object, not storing it yet..
18                                 return object;
19                             }
20                             // 循环依赖校验,并将加入singletonsCurrentlyInCreation
21                             beforeSingletonCreation(beanName);
22                             try {
23                                 object = postProcessObjectFromFactoryBean(object, beanName);
24                             }
25                             catch (Throwable ex) {
26                                 throw new BeanCreationException(beanName,
27                                         "Post-processing of FactoryBean‘s singleton object failed", ex);
28                             }
29                             finally {
30                                 //从singletonsCurrentlyInCreation移除beanName
31                                 afterSingletonCreation(beanName);
32                             }
33                         }
34                         if (containsSingleton(beanName)) {
35                             this.factoryBeanObjectCache.put(beanName, object);
36                         }
37                     }
38                 }
39                 return object;
40             }
41         }
42         else {
43             Object object = doGetObjectFromFactoryBean(factory, beanName);
44             if (shouldPostProcess) {
45                 try {
46                     object = postProcessObjectFromFactoryBean(object, beanName);
47                 }
48                 catch (Throwable ex) {
49                     throw new BeanCreationException(beanName, "Post-processing of FactoryBean‘s object failed", ex);
50                 }
51             }
52             return object;
53         }
54     }
getObjectFromFactoryBean
技术图片
 1     private Object doGetObjectFromFactoryBean(final FactoryBean<?> factory, final String beanName)
 2             throws BeanCreationException {
 3 
 4         Object object;
 5         try {
 6             if (System.getSecurityManager() != null) {
 7                 AccessControlContext acc = getAccessControlContext();
 8                 try {
 9                     object = AccessController.doPrivileged((PrivilegedExceptionAction<Object>) factory::getObject, acc);
10                 }
11                 catch (PrivilegedActionException pae) {
12                     throw pae.getException();
13                 }
14             }
15             else {
16                 object = factory.getObject();
17             }
18         }
19         catch (FactoryBeanNotInitializedException ex) {
20             throw new BeanCurrentlyInCreationException(beanName, ex.toString());
21         }
22         catch (Throwable ex) {
23             throw new BeanCreationException(beanName, "FactoryBean threw exception on object creation", ex);
24         }
25 
26         // Do not accept a null value for a FactoryBean that‘s not fully
27         // initialized yet: Many FactoryBeans just return null then.
28         if (object == null) {
29             if (isSingletonCurrentlyInCreation(beanName)) {
30                 throw new BeanCurrentlyInCreationException(
31                         beanName, "FactoryBean which is currently in creation returned null from getObject");
32             }
33             object = new NullBean();
34         }
35         return object;
36     }
doGetObjectFromFactoryBean
技术图片
1     @Override
2     protected Object postProcessObjectFromFactoryBean(Object object, String beanName) {
3         return applyBeanPostProcessorsAfterInitialization(object, beanName);
4     }
postProcessObjectFromFactoryBean
技术图片
 1     @Override
 2     public Object applyBeanPostProcessorsAfterInitialization(Object existingBean, String beanName)
 3             throws BeansException {
 4 
 5         Object result = existingBean;
 6         for (BeanPostProcessor processor : getBeanPostProcessors()) {
 7             Object current = processor.postProcessAfterInitialization(result, beanName);
 8             if (current == null) {
 9                 return result;
10             }
11             result = current;
12         }
13         return result;
14     }
applyBeanPostProcessorsAfterInitialization

(四)获取单例

技术图片
 1     public Object getSingleton(String beanName, ObjectFactory<?> singletonFactory) {
 2         Assert.notNull(beanName, "Bean name must not be null");
 3         synchronized (this.singletonObjects) {
 4             Object singletonObject = this.singletonObjects.get(beanName);
 5             if (singletonObject == null) {
 6                 if (this.singletonsCurrentlyInDestruction) {
 7                     throw new BeanCreationNotAllowedException(beanName,
 8                             "Singleton bean creation not allowed while singletons of this factory are in destruction " +
 9                             "(Do not request a bean from a BeanFactory in a destroy method implementation!)");
10                 }
11                 if (logger.isDebugEnabled()) {
12                     logger.debug("Creating shared instance of singleton bean ‘" + beanName + "‘");
13                 }
14                 // 记录加载状态
15                 beforeSingletonCreation(beanName);
16                 boolean newSingleton = false;
17                 boolean recordSuppressedExceptions = (this.suppressedExceptions == null);
18                 if (recordSuppressedExceptions) {
19                     this.suppressedExceptions = new LinkedHashSet<>();
20                 }
21                 try {
22                     singletonObject = singletonFactory.getObject();
23                     newSingleton = true;
24                 }
25                 catch (IllegalStateException ex) {
26                     // Has the singleton object implicitly appeared in the meantime ->
27                     // if yes, proceed with it since the exception indicates that state.
28                     singletonObject = this.singletonObjects.get(beanName);
29                     if (singletonObject == null) {
30                         throw ex;
31                     }
32                 }
33                 catch (BeanCreationException ex) {
34                     if (recordSuppressedExceptions) {
35                         for (Exception suppressedException : this.suppressedExceptions) {
36                             ex.addRelatedCause(suppressedException);
37                         }
38                     }
39                     throw ex;
40                 }
41                 finally {
42                     if (recordSuppressedExceptions) {
43                         this.suppressedExceptions = null;
44                     }
45                     afterSingletonCreation(beanName);
46                 }
47                 // 新建的则加入缓存
48                 if (newSingleton) {
49                     addSingleton(beanName, singletonObject);
50                 }
51             }
52             return singletonObject;
53         }
54     }
View Code

(1)缓存中获取

(2)缓存中没有则记录加载状态,创建实例,记录加载状态记录缓存

(五)准备创建bean

技术图片
 1     @Override
 2     protected Object createBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)
 3             throws BeanCreationException {
 4 
 5         if (logger.isTraceEnabled()) {
 6             logger.trace("Creating instance of bean ‘" + beanName + "‘");
 7         }
 8         RootBeanDefinition mbdToUse = mbd;
 9 
10         // Make sure bean class is actually resolved at this point, and
11         // clone the bean definition in case of a dynamically resolved Class
12         // which cannot be stored in the shared merged bean definition.
13         //根据设置的class属性或iclassName来解析Class
14         Class<?> resolvedClass = resolveBeanClass(mbd, beanName);
15         if (resolvedClass != null && !mbd.hasBeanClass() && mbd.getBeanClassName() != null) {
16             mbdToUse = new RootBeanDefinition(mbd);
17             mbdToUse.setBeanClass(resolvedClass);
18         }
19 
20         // Prepare method overrides.
21         //验证及准备覆盖的方法
22         try {
23             mbdToUse.prepareMethodOverrides();
24         }
25         catch (BeanDefinitionValidationException ex) {
26             throw new BeanDefinitionStoreException(mbdToUse.getResourceDescription(),
27                     beanName, "Validation of method overrides failed", ex);
28         }
29 
30         try {
31             // Give BeanPostProcessors a chance to return a proxy instead of the target bean instance.
32             //给BeanPostProcessors一个来返回代理类替代真正实例的机会
33             Object bean = resolveBeforeInstantiation(beanName, mbdToUse);
34             if (bean != null) {
35                 return bean;
36             }
37         }
38         catch (Throwable ex) {
39             throw new BeanCreationException(mbdToUse.getResourceDescription(), beanName,
40                     "BeanPostProcessor before instantiation of bean failed", ex);
41         }
42 
43         try {
44             //创建bean
45             Object beanInstance = doCreateBean(beanName, mbdToUse, args);
46             if (logger.isTraceEnabled()) {
47                 logger.trace("Finished creating instance of bean ‘" + beanName + "‘");
48             }
49             return beanInstance;
50         }
51         catch (BeanCreationException | ImplicitlyAppearedSingletonException ex) {
52             // A previously detected exception with proper bean creation context already,
53             // or illegal singleton state to be communicated up to DefaultSingletonBeanRegistry.
54             throw ex;
55         }
56         catch (Throwable ex) {
57             throw new BeanCreationException(
58                     mbdToUse.getResourceDescription(), beanName, "Unexpected exception during bean creation", ex);
59         }
60     }
createBean

(1)prepareMethodOverrides()

   存在 lookup-method,replace-method配置时,进行方法存在性,以及方法参数校验

(2)resolveBeforeInstantiation()

   实例化前的后置处理器调用,实例化后的后置处理器调用,若无重写则bean==null,进行常规bean创建

(六)创建bean

  1     protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final @Nullable Object[] args)
  2             throws BeanCreationException {
  3 
  4         // Instantiate the bean.
  5         BeanWrapper instanceWrapper = null;
  6         if (mbd.isSingleton()) {
  7             // 单例情况下清除缓存
  8             instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);
  9         }
 10         if (instanceWrapper == null) {
 11             //根据指定的bean使用对应的策略创建新的实例
 12             //将BeanDefinition转化为BeanWrapper
 13             instanceWrapper = createBeanInstance(beanName, mbd, args);
 14         }
 15         final Object bean = instanceWrapper.getWrappedInstance();
 16         Class<?> beanType = instanceWrapper.getWrappedClass();
 17         if (beanType != NullBean.class) {
 18             mbd.resolvedTargetType = beanType;
 19         }
 20 
 21         // Allow post-processors to modify the merged bean definition.
 22         synchronized (mbd.postProcessingLock) {
 23             if (!mbd.postProcessed) {
 24                 try {
 25                     applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);
 26                 }
 27                 catch (Throwable ex) {
 28                     throw new BeanCreationException(mbd.getResourceDescription(), beanName,
 29                             "Post-processing of merged bean definition failed", ex);
 30                 }
 31                 mbd.postProcessed = true;
 32             }
 33         }
 34 
 35         // Eagerly cache singletons to be able to resolve circular references
 36         // even when triggered by lifecycle interfaces like BeanFactoryAware.
 37         // 单例且允许循环依赖且当前bean正在创建中
 38         boolean earlySingletonExposure = (mbd.isSingleton() && this.allowCircularReferences &&
 39                 isSingletonCurrentlyInCreation(beanName));
 40         if (earlySingletonExposure) {
 41             if (logger.isTraceEnabled()) {
 42                 logger.trace("Eagerly caching bean ‘" + beanName +
 43                         "‘ to allow for resolving potential circular references");
 44             }
 45             // !!
 46             addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean));
 47         }
 48 
 49         // Initialize the bean instance.
 50         Object exposedObject = bean;
 51         try {
 52             //对bean进行填充,将属性值注入,存在依赖于其它bean的属性,则递归初始依赖bean
 53             populateBean(beanName, mbd, instanceWrapper);
 54             //调用初始化方法,比如init-method
 55             exposedObject = initializeBean(beanName, exposedObject, mbd);
 56         }
 57         catch (Throwable ex) {
 58             if (ex instanceof BeanCreationException && beanName.equals(((BeanCreationException) ex).getBeanName())) {
 59                 throw (BeanCreationException) ex;
 60             }
 61             else {
 62                 throw new BeanCreationException(
 63                         mbd.getResourceDescription(), beanName, "Initialization of bean failed", ex);
 64             }
 65         }
 66 
 67         if (earlySingletonExposure) {
 68             Object earlySingletonReference = getSingleton(beanName, false);
 69             // 有循环依赖
 70             if (earlySingletonReference != null) {
 71                 // 没有在初始化中被增强
 72                 if (exposedObject == bean) {
 73                     exposedObject = earlySingletonReference;
 74                 }
 75                 else if (!this.allowRawInjectionDespiteWrapping && hasDependentBean(beanName)) {
 76                     String[] dependentBeans = getDependentBeans(beanName);
 77                     Set<String> actualDependentBeans = new LinkedHashSet<>(dependentBeans.length);
 78                     for (String dependentBean : dependentBeans) {
 79                         //以依赖检查
 80                         if (!removeSingletonIfCreatedForTypeCheckOnly(dependentBean)) {
 81                             actualDependentBeans.add(dependentBean);
 82                         }
 83                     }
 84                     // 存在循环依赖
 85                     if (!actualDependentBeans.isEmpty()) {
 86                         throw new BeanCurrentlyInCreationException(beanName,
 87                                 "Bean with name ‘" + beanName + "‘ has been injected into other beans [" +
 88                                 StringUtils.collectionToCommaDelimitedString(actualDependentBeans) +
 89                                 "] in its raw version as part of a circular reference, but has eventually been " +
 90                                 "wrapped. This means that said other beans do not use the final version of the " +
 91                                 "bean. This is often the result of over-eager type matching - consider using " +
 92                                 "‘getBeanNamesOfType‘ with the ‘allowEagerInit‘ flag turned off, for example.");
 93                     }
 94                 }
 95             }
 96         }
 97 
 98         // Register bean as disposable.
 99         try {
100             //根据scope注册bean
101             registerDisposableBeanIfNecessary(beanName, bean, mbd);
102         }
103         catch (BeanDefinitionValidationException ex) {
104             throw new BeanCreationException(
105                     mbd.getResourceDescription(), beanName, "Invalid destruction signature", ex);
106         }
107 
108         return exposedObject;
109     }

(1)创建bean实例

技术图片
 1     protected BeanWrapper createBeanInstance(String beanName, RootBeanDefinition mbd, @Nullable Object[] args) {
 2         // Make sure bean class is actually resolved at this point.
 3         Class<?> beanClass = resolveBeanClass(mbd, beanName);
 4 
 5         if (beanClass != null && !Modifier.isPublic(beanClass.getModifiers()) && !mbd.isNonPublicAccessAllowed()) {
 6             throw new BeanCreationException(mbd.getResourceDescription(), beanName,
 7                     "Bean class isn‘t public, and non-public access not allowed: " + beanClass.getName());
 8         }
 9 
10         Supplier<?> instanceSupplier = mbd.getInstanceSupplier();
11         if (instanceSupplier != null) {
12             return obtainFromSupplier(instanceSupplier, beanName);
13         }
14 
15         if (mbd.getFactoryMethodName() != null) {
16             // 工厂方法
17             return instantiateUsingFactoryMethod(beanName, mbd, args);
18         }
19 
20         // Shortcut when re-creating the same bean...
21         boolean resolved = false;
22         boolean autowireNecessary = false;
23         if (args == null) {
24             synchronized (mbd.constructorArgumentLock) {
25                 if (mbd.resolvedConstructorOrFactoryMethod != null) {
26                     resolved = true;
27                     autowireNecessary = mbd.constructorArgumentsResolved;
28                 }
29             }
30         }
31         if (resolved) {
32             if (autowireNecessary) {
33                 //构造函数自动注入
34                 return autowireConstructor(beanName, mbd, null, null);
35             }
36             else {
37                 //默认构造函数注入
38                 return instantiateBean(beanName, mbd);
39             }
40         }
41 
42         // Candidate constructors for autowiring?
43         Constructor<?>[] ctors = determineConstructorsFromBeanPostProcessors(beanClass, beanName);
44         if (ctors != null || mbd.getResolvedAutowireMode() == AUTOWIRE_CONSTRUCTOR ||
45                 mbd.hasConstructorArgumentValues() || !ObjectUtils.isEmpty(args)) {
46             //构造函数自动注入
47             return autowireConstructor(beanName, mbd, ctors, args);
48         }
49 
50         // Preferred constructors for default construction?
51         ctors = mbd.getPreferredConstructors();
52         if (ctors != null) {
53             //构造函数自动注入
54             return autowireConstructor(beanName, mbd, ctors, null);
55         }
56 
57         // No special handling: simply use no-arg constructor.
58         //默认构造函数注入
59         return instantiateBean(beanName, mbd);
60     }
createBeanInstance

(a)autowireConstructor

  (b)   instantiateBean

(2)属性注入

 1     protected void populateBean(String beanName, RootBeanDefinition mbd, @Nullable BeanWrapper bw) {
 2         if (bw == null) {
 3             if (mbd.hasPropertyValues()) {
 4                 throw new BeanCreationException(
 5                         mbd.getResourceDescription(), beanName, "Cannot apply property values to null instance");
 6             }
 7             else {
 8                 // Skip property population phase for null instance.
 9                 return;
10             }
11         }
12 
13         // Give any InstantiationAwareBeanPostProcessors the opportunity to modify the
14         // state of the bean before properties are set. This can be used, for example,
15         // to support styles of field injection.
16         if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
17             for (BeanPostProcessor bp : getBeanPostProcessors()) {
18                 if (bp instanceof InstantiationAwareBeanPostProcessor) {
19                     InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
20                     if (!ibp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) {
21                         return;
22                     }
23                 }
24             }
25         }
26 
27         PropertyValues pvs = (mbd.hasPropertyValues() ? mbd.getPropertyValues() : null);
28 
29         int resolvedAutowireMode = mbd.getResolvedAutowireMode();
30         if (resolvedAutowireMode == AUTOWIRE_BY_NAME || resolvedAutowireMode == AUTOWIRE_BY_TYPE) {
31             MutablePropertyValues newPvs = new MutablePropertyValues(pvs);
32             // Add property values based on autowire by name if applicable.
33             if (resolvedAutowireMode == AUTOWIRE_BY_NAME) {
34                 autowireByName(beanName, mbd, bw, newPvs);
35             }
36             // Add property values based on autowire by type if applicable.
37             if (resolvedAutowireMode == AUTOWIRE_BY_TYPE) {
38                 autowireByType(beanName, mbd, bw, newPvs);
39             }
40             pvs = newPvs;
41         }
42 
43         // 后处理器已初始化
44         boolean hasInstAwareBpps = hasInstantiationAwareBeanPostProcessors();
45         // 需要依赖校验
46         boolean needsDepCheck = (mbd.getDependencyCheck() != AbstractBeanDefinition.DEPENDENCY_CHECK_NONE);
47 
48         PropertyDescriptor[] filteredPds = null;
49         if (hasInstAwareBpps) {
50             if (pvs == null) {
51                 pvs = mbd.getPropertyValues();
52             }
53             for (BeanPostProcessor bp : getBeanPostProcessors()) {
54                 if (bp instanceof InstantiationAwareBeanPostProcessor) {
55                     InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
56                     PropertyValues pvsToUse = ibp.postProcessProperties(pvs, bw.getWrappedInstance(), beanName);
57                     if (pvsToUse == null) {
58                         if (filteredPds == null) {
59                             filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
60                         }
61                         pvsToUse = ibp.postProcessPropertyValues(pvs, filteredPds, bw.getWrappedInstance(), beanName);
62                         if (pvsToUse == null) {
63                             return;
64                         }
65                     }
66                     pvs = pvsToUse;
67                 }
68             }
69         }
70         if (needsDepCheck) {
71             if (filteredPds == null) {
72                 filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
73             }
74             checkDependencies(beanName, mbd, filteredPds, pvs);
75         }
76 
77         if (pvs != null) {
78             // 将属性应用到bean中
79             applyPropertyValues(beanName, mbd, bw, pvs);
80         }
81     }

(a)autowireByName

(b)autowireByType

(c)applyPropertyValues

(3)初始化bean

 1     protected Object initializeBean(final String beanName, final Object bean, @Nullable RootBeanDefinition mbd) {
 2         if (System.getSecurityManager() != null) {
 3             AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
 4                 invokeAwareMethods(beanName, bean);
 5                 return null;
 6             }, getAccessControlContext());
 7         }
 8         else {
 9             // 对特殊的bean处理
10             invokeAwareMethods(beanName, bean);
11         }
12 
13         Object wrappedBean = bean;
14         if (mbd == null || !mbd.isSynthetic()) {
15             // 后处理器
16             wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
17         }
18 
19         try {
20             // 激活用户自定义的init方法
21             invokeInitMethods(beanName, wrappedBean, mbd);
22         }
23         catch (Throwable ex) {
24             throw new BeanCreationException(
25                     (mbd != null ? mbd.getResourceDescription() : null),
26                     beanName, "Invocation of init method failed", ex);
27         }
28         if (mbd == null || !mbd.isSynthetic()) {
29             // 后处理器应用
30             wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
31         }
32 
33         return wrappedBean;
34     }

(a)invokeAwareMethods

(b)applyBeanPostProcessorsBeforeInitialization

(c)invokeInitMethods

(d)applyBeanPostProcessorsAfterInitialization

(4)注册DisposableBean

 1     protected void registerDisposableBeanIfNecessary(String beanName, Object bean, RootBeanDefinition mbd) {
 2         AccessControlContext acc = (System.getSecurityManager() != null ? getAccessControlContext() : null);
 3         if (!mbd.isPrototype() && requiresDestruction(bean, mbd)) {
 4             if (mbd.isSingleton()) {
 5                 // Register a DisposableBean implementation that performs all destruction
 6                 // work for the given bean: DestructionAwareBeanPostProcessors,
 7                 // DisposableBean interface, custom destroy method.
 8                 
 9                 registerDisposableBean(beanName,
10                         new DisposableBeanAdapter(bean, beanName, mbd, getBeanPostProcessors(), acc));
11             } else {
12                 
13                 // A bean with a custom scope...
14                 Scope scope = this.scopes.get(mbd.getScope());
15                 if (scope == null) {
16                     throw new IllegalStateException("No Scope registered for scope name ‘" + mbd.getScope() + "‘");
17                 }
18                 
19                 scope.registerDestructionCallback(beanName,
20                         new DisposableBeanAdapter(bean, beanName, mbd, getBeanPostProcessors(), acc));
21             }
22         }
23     }

 

以上是关于Spring源码学习bean的加载的主要内容,如果未能解决你的问题,请参考以下文章

10Spring 源码学习 ~ Bean 的加载步骤详解

Spring源码学习笔记1

Spring源码学习笔记——Bean加载

Spring源码学习~11Bean 的加载步骤详解

Spring源码学习~11Bean 的加载步骤详解

520就应该和女朋友一起学习Spring源码——Bean加载