文章结构

  1. 开篇先介绍了conversionServiceEmbeddedValueResolver两个比较有意思的东东
  2. 然后就是重点的bean的初始化
  3. 初始化过程中涉及到了singletonprototype两个Scope的bean的处理
  4. 当然,还有令人头疼的循环依赖问题
  5. 创建bean的过程中还有我们熟悉的@Autowired注解注入属性的方式
  6. 接着就是一些清除缓存的操作

本篇文章是SpringIOC源码解析(上)的续集,上一篇文章介绍了使用XML的方式启动Spring,然后追踪了BeanFactory容器的创建、配置文件的解析、Bean的注册等,本篇文章继续分析Bean的初始化流程

12. finishBeanFactoryInitialization()

前方超长篇幅预警。。。

刚才我们提到了bean还没有初始化。这个方法就是负责初始化所有的没有设置懒加载的singleton bean

  1. protected void finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory) {
  2. if (beanFactory.containsBean(CONVERSION_SERVICE_BEAN_NAME) &&
  3. beanFactory.isTypeMatch(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class)) {
  4. beanFactory.setConversionService(
  5. beanFactory.getBean(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class));
  6. }
  7. if (!beanFactory.hasEmbeddedValueResolver()) {
  8. beanFactory.addEmbeddedValueResolver(strVal -> getEnvironment().resolvePlaceholders(strVal));
  9. }
  10. //先初始化 LoadTimeWeaverAware 类型的 Bean
  11. String[] weaverAwareNames = beanFactory.getBeanNamesForType(LoadTimeWeaverAware.class, false, false);
  12. for (String weaverAwareName : weaverAwareNames) {
  13. getBean(weaverAwareName);
  14. }
  15. //停止使用用于类型匹配的临时类加载器
  16. beanFactory.setTempClassLoader(null);
  17. //冻结所有的bean定义,即已注册的bean定义将不会被修改或后处理
  18. beanFactory.freezeConfiguration();
  19. //初始化
  20. beanFactory.preInstantiateSingletons();
  21. }

上方没有解释的代码往下看吧

conversionService

这种类型的bean最实用的场景就是用来将前端传过来的参数和后端的controller方法上的参数格式转换的时候使用

例如:前端要传一个String,后端使用Date接受的时候就可以这样操作

  1. public class StringToDateConverter implements Converter<String, Date> {
  2. @Override
  3. public Date convert(String date) {
  4. try {
  5. return dateFormat.parse(date);
  6. } catch (Exception e) {
  7. e.printStackTrace();
  8. System.out.println("日期转换失败!");
  9. return null;
  10. }
  11. }
  12. }

再搞个bean

  1. <bean id="conversionService"
  2. class="org.springframework.context.support.ConversionServiceFactoryBean">
  3. <property name="converters">
  4. <list>
  5. <bean class="cn.shiyujun.utils.StringToDateConverter"/>
  6. </list>
  7. </property>
  8. </bean>

EmbeddedValueResolver

利用EmbeddedValueResolver可以很方便的实现读取配置文件的属性

  1. @Component
  2. public class PropertiesUtil implements EmbeddedValueResolverAware {
  3. private StringValueResolver resolver;
  4. @Override
  5. public void setEmbeddedValueResolver(StringValueResolver resolver) {
  6. this.resolver = resolver;
  7. }
  8. /**
  9. * 获取属性时直接传入属性名称即可
  10. */
  11. public String getPropertiesValue(String key) {
  12. StringBuilder name = new StringBuilder("${").append(key).append("}");
  13. return resolver.resolveStringValue(name.toString());
  14. }
  15. }

初始化

敲黑板了,重点来了。。。

preInstantiateSingletons()

这里分析beanFactory.preInstantiateSingletons()方法

  1. public void preInstantiateSingletons() throws BeansException {
  2. if (this.logger.isDebugEnabled()) {
  3. this.logger.debug("Pre-instantiating singletons in " + this);
  4. }
  5. // this.beanDefinitionNames 保存了所有的 beanNames
  6. List<String> beanNames = new ArrayList<String>(this.beanDefinitionNames);
  7. for (String beanName : beanNames) {
  8. // 合并父 Bean 中的配置,主意<bean id="" class="" parent="" /> 中的 parent属性
  9. RootBeanDefinition bd = getMergedLocalBeanDefinition(beanName);
  10. // 不是抽象类、是单例的且不是懒加载的
  11. if (!bd.isAbstract() && bd.isSingleton() && !bd.isLazyInit()) {
  12. // 处理 FactoryBean
  13. if (isFactoryBean(beanName)) {
  14. //在 beanName 前面加上“&” 符号
  15. final FactoryBean<?> factory = (FactoryBean<?>) getBean(FACTORY_BEAN_PREFIX + beanName);
  16. // 判断当前 FactoryBean 是否是 SmartFactoryBean 的实现
  17. boolean isEagerInit;
  18. if (System.getSecurityManager() != null && factory instanceof SmartFactoryBean) {
  19. isEagerInit = AccessController.doPrivileged(new PrivilegedAction<Boolean>() {
  20. @Override
  21. public Boolean run() {
  22. return ((SmartFactoryBean<?>) factory).isEagerInit();
  23. }
  24. }, getAccessControlContext());
  25. }
  26. else {
  27. isEagerInit = (factory instanceof SmartFactoryBean &&
  28. ((SmartFactoryBean<?>) factory).isEagerInit());
  29. }
  30. if (isEagerInit) {
  31. getBean(beanName);
  32. }
  33. }
  34. else {
  35. // 不是FactoryBean的直接使用此方法进行初始化
  36. getBean(beanName);
  37. }
  38. }
  39. }
  40. // 如果bean实现了 SmartInitializingSingleton 接口的,那么在这里得到回调
  41. for (String beanName : beanNames) {
  42. Object singletonInstance = getSingleton(beanName);
  43. if (singletonInstance instanceof SmartInitializingSingleton) {
  44. final SmartInitializingSingleton smartSingleton = (SmartInitializingSingleton) singletonInstance;
  45. if (System.getSecurityManager() != null) {
  46. AccessController.doPrivileged(new PrivilegedAction<Object>() {
  47. @Override
  48. public Object run() {
  49. smartSingleton.afterSingletonsInstantiated();
  50. return null;
  51. }
  52. }, getAccessControlContext());
  53. }
  54. else {
  55. smartSingleton.afterSingletonsInstantiated();
  56. }
  57. }
  58. }
  59. }

getBean(beanName)

可以看到,不管是不是FactoryBean,最后都调用了getBean(beanName),继续看这个方法吧

  1. @Override
  2. public Object getBean(String name) throws BeansException {
  3. return doGetBean(name, null, null, false);
  4. }
  5. protected <T> T doGetBean(
  6. final String name, final Class<T> requiredType, final Object[] args, boolean typeCheckOnly)
  7. throws BeansException {
  8. // 获取beanName,处理两种情况,一个是前面说的 FactoryBean(前面带 ‘&’),再一个这个方法是可以根据别名来获取Bean的,所以在这里是要转换成最正统的BeanName
  9. //主要逻辑就是如果是FactoryBean就把&去掉如果是别名就把根据别名获取真实名称后面就不贴代码了
  10. final String beanName = transformedBeanName(name);
  11. //最后的返回值
  12. Object bean;
  13. // 检查是否已初始化
  14. Object sharedInstance = getSingleton(beanName);
  15. //如果已经初始化过了,且没有传args参数就代表是get,直接取出返回
  16. if (sharedInstance != null && args == null) {
  17. if (logger.isDebugEnabled()) {
  18. if (isSingletonCurrentlyInCreation(beanName)) {
  19. logger.debug("...");
  20. }
  21. else {
  22. logger.debug("Returning cached instance of singleton bean '" + beanName + "'");
  23. }
  24. }
  25. // 这里如果是普通Bean 的话,直接返回,如果是 FactoryBean 的话,返回它创建的那个实例对象
  26. bean = getObjectForBeanInstance(sharedInstance, name, beanName, null);
  27. }
  28. else {
  29. // 如果存在prototype类型的这个bean
  30. if (isPrototypeCurrentlyInCreation(beanName)) {
  31. throw new BeanCurrentlyInCreationException(beanName);
  32. }
  33. // 如果当前BeanDefinition不存在这个bean且具有父BeanFactory
  34. BeanFactory parentBeanFactory = getParentBeanFactory();
  35. if (parentBeanFactory != null && !containsBeanDefinition(beanName)) {
  36. String nameToLookup = originalBeanName(name);
  37. // 返回父容器的查询结果
  38. if (args != null) {
  39. return (T) parentBeanFactory.getBean(nameToLookup, args);
  40. }
  41. else {
  42. return parentBeanFactory.getBean(nameToLookup, requiredType);
  43. }
  44. }
  45. if (!typeCheckOnly) {
  46. // typeCheckOnly 为 false,将当前 beanName 放入一个 alreadyCreated 的 Set 集合中。
  47. markBeanAsCreated(beanName);
  48. }
  49. /*
  50. * 到这就要创建bean了
  51. */
  52. try {
  53. final RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
  54. checkMergedBeanDefinition(mbd, beanName, args);
  55. // 先初始化依赖的所有 Bean, depends-on 中定义的依赖
  56. String[] dependsOn = mbd.getDependsOn();
  57. if (dependsOn != null) {
  58. for (String dep : dependsOn) {
  59. // 检查是不是有循环依赖
  60. if (isDependent(beanName, dep)) {
  61. throw new BeanCreationException(mbd.getResourceDescription(), beanName,
  62. "Circular depends-on relationship between '" + beanName + "' and '" + dep + "'");
  63. }
  64. // 注册一下依赖关系
  65. registerDependentBean(dep, beanName);
  66. // 先初始化被依赖项
  67. getBean(dep);
  68. }
  69. }
  70. // 如果是单例的
  71. if (mbd.isSingleton()) {
  72. sharedInstance = getSingleton(beanName, new ObjectFactory<Object>() {
  73. @Override
  74. public Object getObject() throws BeansException {
  75. try {
  76. // 执行创建 Bean,下面说
  77. return createBean(beanName, mbd, args);
  78. }
  79. catch (BeansException ex) {
  80. destroySingleton(beanName);
  81. throw ex;
  82. }
  83. }
  84. });
  85. bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
  86. }
  87. // 如果是prototype
  88. else if (mbd.isPrototype()) {
  89. Object prototypeInstance = null;
  90. try {
  91. beforePrototypeCreation(beanName);
  92. // 执行创建 Bean
  93. prototypeInstance = createBean(beanName, mbd, args);
  94. }
  95. finally {
  96. afterPrototypeCreation(beanName);
  97. }
  98. bean = getObjectForBeanInstance(prototypeInstance, name, beanName, mbd);
  99. }
  100. // 如果不是 singleton 和 prototype 那么就是自定义的scope、例如Web项目中的session等类型,这里就交给自定义scope的应用方去实现
  101. else {
  102. String scopeName = mbd.getScope();
  103. final Scope scope = this.scopes.get(scopeName);
  104. if (scope == null) {
  105. throw new IllegalStateException("No Scope registered for scope name '" + scopeName + "'");
  106. }
  107. try {
  108. Object scopedInstance = scope.get(beanName, new ObjectFactory<Object>() {
  109. @Override
  110. public Object getObject() throws BeansException {
  111. beforePrototypeCreation(beanName);
  112. try {
  113. // 执行创建 Bean
  114. return createBean(beanName, mbd, args);
  115. }
  116. finally {
  117. afterPrototypeCreation(beanName);
  118. }
  119. }
  120. });
  121. bean = getObjectForBeanInstance(scopedInstance, name, beanName, mbd);
  122. }
  123. catch (IllegalStateException ex) {
  124. throw new BeanCreationException(beanName,
  125. "Scope '" + scopeName + "' is not active for the current thread; consider " +
  126. "defining a scoped proxy for this bean if you intend to refer to it from a singleton",
  127. ex);
  128. }
  129. }
  130. }
  131. catch (BeansException ex) {
  132. cleanupAfterBeanCreationFailure(beanName);
  133. throw ex;
  134. }
  135. }
  136. //检查bean的类型
  137. if (requiredType != null && bean != null && !requiredType.isInstance(bean)) {
  138. try {
  139. return getTypeConverter().convertIfNecessary(bean, requiredType);
  140. }
  141. catch (TypeMismatchException ex) {
  142. if (logger.isDebugEnabled()) {
  143. logger.debug("Failed to convert bean '" + name + "' to required type '" +
  144. ClassUtils.getQualifiedName(requiredType) + "'", ex);
  145. }
  146. throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass());
  147. }
  148. }
  149. return (T) bean;
  150. }

看了上方方法我们知道了原来Spring本身只定义了两种Scope,也知道了SpringMVC的几种Scope是如何实现的了。
然后发现一开始会先判断bean存不存在,如果存在就直接返回了。如果不存在那就要接着往下看createBean方法了

createBean

  1. protected Object createBean(String beanName, RootBeanDefinition mbd, Object[] args) throws BeanCreationException {
  2. if (logger.isDebugEnabled()) {
  3. logger.debug("Creating instance of bean '" + beanName + "'");
  4. }
  5. RootBeanDefinition mbdToUse = mbd;
  6. // 确保 BeanDefinition 中的 Class 被加载
  7. Class<?> resolvedClass = resolveBeanClass(mbd, beanName);
  8. if (resolvedClass != null && !mbd.hasBeanClass() && mbd.getBeanClassName() != null) {
  9. mbdToUse = new RootBeanDefinition(mbd);
  10. mbdToUse.setBeanClass(resolvedClass);
  11. }
  12. // 准备方法覆写,如果bean中定义了 <lookup-method /> 和 <replaced-method />
  13. try {
  14. mbdToUse.prepareMethodOverrides();
  15. }
  16. catch (BeanDefinitionValidationException ex) {
  17. throw new BeanDefinitionStoreException(mbdToUse.getResourceDescription(),
  18. beanName, "Validation of method overrides failed", ex);
  19. }
  20. try {
  21. // 如果有代理的话直接返回
  22. Object bean = resolveBeforeInstantiation(beanName, mbdToUse);
  23. if (bean != null) {
  24. return bean;
  25. }
  26. }
  27. catch (Throwable ex) {
  28. throw new BeanCreationException(mbdToUse.getResourceDescription(), beanName,
  29. "BeanPostProcessor before instantiation of bean failed", ex);
  30. }
  31. // 创建 bean
  32. Object beanInstance = doCreateBean(beanName, mbdToUse, args);
  33. if (logger.isDebugEnabled()) {
  34. logger.debug("Finished creating instance of bean '" + beanName + "'");
  35. }
  36. return beanInstance;
  37. }
  38. protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final Object[] args)
  39. throws BeanCreationException {
  40. BeanWrapper instanceWrapper = null;
  41. if (mbd.isSingleton()) {
  42. //如果是.factoryBean则从缓存删除
  43. instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);
  44. }
  45. if (instanceWrapper == null) {
  46. // 实例化 Bean,这个方法里面才是终点,下面说
  47. instanceWrapper = createBeanInstance(beanName, mbd, args);
  48. }
  49. //bean实例
  50. final Object bean = (instanceWrapper != null ? instanceWrapper.getWrappedInstance() : null);
  51. //bean类型
  52. Class<?> beanType = (instanceWrapper != null ? instanceWrapper.getWrappedClass() : null);
  53. mbd.resolvedTargetType = beanType;
  54. synchronized (mbd.postProcessingLock) {
  55. if (!mbd.postProcessed) {
  56. try {
  57. // 循环调用实现了MergedBeanDefinitionPostProcessor接口的postProcessMergedBeanDefinition方法
  58. // Spring对这个接口有几个默认的实现,其中大家最熟悉的一个是操作@Autowired注解的
  59. applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);
  60. }
  61. catch (Throwable ex) {
  62. throw new BeanCreationException(mbd.getResourceDescription(), beanName,
  63. "Post-processing of merged bean definition failed", ex);
  64. }
  65. mbd.postProcessed = true;
  66. }
  67. }
  68. // 解决循环依赖问题
  69. boolean earlySingletonExposure = (mbd.isSingleton() && this.allowCircularReferences &&
  70. isSingletonCurrentlyInCreation(beanName));
  71. if (earlySingletonExposure) {
  72. if (logger.isDebugEnabled()) {
  73. logger.debug("Eagerly caching bean '" + beanName +
  74. "' to allow for resolving potential circular references");
  75. }
  76. //当正在创建A时,A依赖B,此时通过(8将A作为ObjectFactory放入单例工厂中进行early expose,此处B需要引用A,但A正在创建,从单例工厂拿到ObjectFactory,从而允许循环依赖
  77. addSingletonFactory(beanName, new ObjectFactory<Object>() {
  78. @Override
  79. public Object getObject() throws BeansException {
  80. return getEarlyBeanReference(beanName, mbd, bean);
  81. }
  82. });
  83. }
  84. Object exposedObject = bean;
  85. try {
  86. // 负责属性装配,很重要,下面说
  87. populateBean(beanName, mbd, instanceWrapper);
  88. if (exposedObject != null) {
  89. // 这里是处理bean初始化完成后的各种回调,例如init-method、InitializingBean 接口、BeanPostProcessor 接口
  90. exposedObject = initializeBean(beanName, exposedObject, mbd);
  91. }
  92. }
  93. catch (Throwable ex) {
  94. if (ex instanceof BeanCreationException && beanName.equals(((BeanCreationException) ex).getBeanName())) {
  95. throw (BeanCreationException) ex;
  96. }
  97. else {
  98. throw new BeanCreationException(
  99. mbd.getResourceDescription(), beanName, "Initialization of bean failed", ex);
  100. }
  101. }
  102. //同样的,如果存在循环依赖
  103. if (earlySingletonExposure) {
  104. Object earlySingletonReference = getSingleton(beanName, false);
  105. if (earlySingletonReference != null) {
  106. if (exposedObject == bean) {
  107. exposedObject = earlySingletonReference;
  108. }
  109. else if (!this.allowRawInjectionDespiteWrapping && hasDependentBean(beanName)) {
  110. String[] dependentBeans = getDependentBeans(beanName);
  111. Set<String> actualDependentBeans = new LinkedHashSet<String>(dependentBeans.length);
  112. for (String dependentBean : dependentBeans) {
  113. if (!removeSingletonIfCreatedForTypeCheckOnly(dependentBean)) {
  114. actualDependentBeans.add(dependentBean);
  115. }
  116. }
  117. if (!actualDependentBeans.isEmpty()) {
  118. throw new BeanCurrentlyInCreationException(beanName,
  119. "Bean with name '" + beanName + "' has been injected into other beans [" +
  120. StringUtils.collectionToCommaDelimitedString(actualDependentBeans) +
  121. "] in its raw version as part of a circular reference, but has eventually been " +
  122. "wrapped. This means that said other beans do not use the final version of the " +
  123. "bean. This is often the result of over-eager type matching - consider using " +
  124. "'getBeanNamesOfType' with the 'allowEagerInit' flag turned off, for example.");
  125. }
  126. }
  127. }
  128. }
  129. // 把bean注册到相应的Scope中
  130. try {
  131. registerDisposableBeanIfNecessary(beanName, bean, mbd);
  132. }
  133. catch (BeanDefinitionValidationException ex) {
  134. throw new BeanCreationException(
  135. mbd.getResourceDescription(), beanName, "Invalid destruction signature", ex);
  136. }
  137. return exposedObject;
  138. }

到这里第一次初始化的bean也返回了,你以为就这样结束了么。不,还有几个很重要的点

创建bean实例createBeanInstance ()

  1. protected BeanWrapper createBeanInstance(String beanName, RootBeanDefinition mbd, Object[] args) {
  2. // 确保已经加载了此 class
  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. if (mbd.getFactoryMethodName() != null) {
  10. // 采用工厂方法实例化
  11. return instantiateUsingFactoryMethod(beanName, mbd, args);
  12. }
  13. //是否第一次
  14. boolean resolved = false;
  15. //是否采用构造函数注入
  16. boolean autowireNecessary = false;
  17. if (args == null) {
  18. synchronized (mbd.constructorArgumentLock) {
  19. if (mbd.resolvedConstructorOrFactoryMethod != null) {
  20. resolved = true;
  21. autowireNecessary = mbd.constructorArgumentsResolved;
  22. }
  23. }
  24. }
  25. if (resolved) {
  26. if (autowireNecessary) {
  27. return autowireConstructor(beanName, mbd, null, null);
  28. }
  29. else {
  30. // 无参构造函数
  31. return instantiateBean(beanName, mbd);
  32. }
  33. }
  34. // 判断是否采用有参构造函数
  35. Constructor<?>[] ctors = determineConstructorsFromBeanPostProcessors(beanClass, beanName);
  36. if (ctors != null ||
  37. mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_CONSTRUCTOR ||
  38. mbd.hasConstructorArgumentValues() || !ObjectUtils.isEmpty(args)) {
  39. // 构造函数依赖注入
  40. return autowireConstructor(beanName, mbd, ctors, args);
  41. }
  42. // 调用无参构造函数
  43. return instantiateBean(beanName, mbd);
  44. }

选一个无参的构造看一下吧

  1. protected BeanWrapper instantiateBean(final String beanName, final RootBeanDefinition mbd) {
  2. try {
  3. Object beanInstance;
  4. final BeanFactory parent = this;
  5. if (System.getSecurityManager() != null) {
  6. beanInstance = AccessController.doPrivileged(new PrivilegedAction<Object>() {
  7. @Override
  8. public Object run() {
  9. return getInstantiationStrategy().instantiate(mbd, beanName, parent);
  10. }
  11. }, getAccessControlContext());
  12. }
  13. else {
  14. // 具体实例化的实现,往下看
  15. beanInstance = getInstantiationStrategy().instantiate(mbd, beanName, parent);
  16. }
  17. BeanWrapper bw = new BeanWrapperImpl(beanInstance);
  18. initBeanWrapper(bw);
  19. return bw;
  20. }
  21. catch (Throwable ex) {
  22. throw new BeanCreationException(
  23. mbd.getResourceDescription(), beanName, "Instantiation of bean failed", ex);
  24. }
  25. }
  26. public Object instantiate(RootBeanDefinition bd, String beanName, BeanFactory owner) {
  27. // 如果不存在方法覆写,那就使用 java 反射进行实例化,否则使用 CGLIB,
  28. if (bd.getMethodOverrides().isEmpty()) {
  29. Constructor<?> constructorToUse;
  30. synchronized (bd.constructorArgumentLock) {
  31. constructorToUse = (Constructor<?>) bd.resolvedConstructorOrFactoryMethod;
  32. if (constructorToUse == null) {
  33. final Class<?> clazz = bd.getBeanClass();
  34. if (clazz.isInterface()) {
  35. throw new BeanInstantiationException(clazz, "Specified class is an interface");
  36. }
  37. try {
  38. if (System.getSecurityManager() != null) {
  39. constructorToUse = AccessController.doPrivileged(new PrivilegedExceptionAction<Constructor<?>>() {
  40. @Override
  41. public Constructor<?> run() throws Exception {
  42. return clazz.getDeclaredConstructor((Class[]) null);
  43. }
  44. });
  45. }
  46. else {
  47. constructorToUse = clazz.getDeclaredConstructor((Class[]) null);
  48. }
  49. bd.resolvedConstructorOrFactoryMethod = constructorToUse;
  50. }
  51. catch (Throwable ex) {
  52. throw new BeanInstantiationException(clazz, "No default constructor found", ex);
  53. }
  54. }
  55. }
  56. // 利用构造方法进行实例化
  57. return BeanUtils.instantiateClass(constructorToUse);
  58. }
  59. else {
  60. // 存在方法覆写,利用 CGLIB 来完成实例化,需要依赖于 CGLIB 生成子类,这里就不展开了
  61. return instantiateWithMethodInjection(bd, beanName, owner);
  62. }
  63. }

bean属性注入populateBean ()

  1. protected void populateBean(String beanName, RootBeanDefinition mbd, BeanWrapper bw) {
  2. // bean的所有属性
  3. PropertyValues pvs = mbd.getPropertyValues();
  4. if (bw == null) {
  5. if (!pvs.isEmpty()) {
  6. throw new BeanCreationException(
  7. mbd.getResourceDescription(), beanName, "Cannot apply property values to null instance");
  8. }
  9. else {
  10. return;
  11. }
  12. }
  13. boolean continueWithPropertyPopulation = true;
  14. if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
  15. for (BeanPostProcessor bp : getBeanPostProcessors()) {
  16. if (bp instanceof InstantiationAwareBeanPostProcessor) {
  17. InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
  18. // 如果返回 false,代表不需要进行后续的属性设值,也不需要再经过其他的 BeanPostProcessor 的处理
  19. if (!ibp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) {
  20. continueWithPropertyPopulation = false;
  21. break;
  22. }
  23. }
  24. }
  25. }
  26. if (!continueWithPropertyPopulation) {
  27. return;
  28. }
  29. if (mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_NAME ||
  30. mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_TYPE) {
  31. MutablePropertyValues newPvs = new MutablePropertyValues(pvs);
  32. // 通过名字找到所有属性值,如果是 bean 依赖,先初始化依赖的 bean。记录依赖关系
  33. if (mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_NAME) {
  34. autowireByName(beanName, mbd, bw, newPvs);
  35. }
  36. // 通过类型装配。复杂一些
  37. if (mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_TYPE) {
  38. autowireByType(beanName, mbd, bw, newPvs);
  39. }
  40. pvs = newPvs;
  41. }
  42. boolean hasInstAwareBpps = hasInstantiationAwareBeanPostProcessors();
  43. boolean needsDepCheck = (mbd.getDependencyCheck() != RootBeanDefinition.DEPENDENCY_CHECK_NONE);
  44. if (hasInstAwareBpps || needsDepCheck) {
  45. PropertyDescriptor[] filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
  46. if (hasInstAwareBpps) {
  47. for (BeanPostProcessor bp : getBeanPostProcessors()) {
  48. if (bp instanceof InstantiationAwareBeanPostProcessor) {
  49. InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
  50. // 这里就是上方曾经提到过得对@Autowired处理的一个BeanPostProcessor了
  51. // 它会对所有标记@Autowired、@Value 注解的属性进行设值
  52. pvs = ibp.postProcessPropertyValues(pvs, filteredPds, bw.getWrappedInstance(), beanName);
  53. if (pvs == null) {
  54. return;
  55. }
  56. }
  57. }
  58. }
  59. if (needsDepCheck) {
  60. checkDependencies(beanName, mbd, filteredPds, pvs);
  61. }
  62. }
  63. // 设置 bean 实例的属性值
  64. applyPropertyValues(beanName, mbd, bw, pvs);
  65. }

getBean这一块就搞完了

13. finishRefresh()

  1. protected void finishRefresh() {
  2. //看名字就知道了,清理刚才一系列操作使用到的资源缓存
  3. clearResourceCaches();
  4. // 初始化LifecycleProcessor
  5. initLifecycleProcessor();
  6. // 这个方法的内部实现是启动所有实现了Lifecycle接口的bean
  7. getLifecycleProcessor().onRefresh();
  8. //发布ContextRefreshedEvent事件
  9. publishEvent(new ContextRefreshedEvent(this));
  10. // 检查spring.liveBeansView.mbeanDomain是否存在,有就会创建一个MBeanServer
  11. LiveBeansView.registerApplicationContext(this);
  12. }

14. resetCommonCaches()

最后一步还是清除缓存

15. refresh()总结

上方以及之前的一篇文章,用了这么长的篇幅把整个refresh()方法的细节给梳理清楚,这里再把刚开始看的懵懵的refresh()方法贴一下

  1. public void refresh() throws BeansException, IllegalStateException {
  2. synchronized (this.startupShutdownMonitor) {
  3. // 记录容器的启动时间、标记“已启动”状态、检查环境变量
  4. prepareRefresh();
  5. // 初始化BeanFactory容器、注册BeanDefinition
  6. ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
  7. // 设置 BeanFactory 的类加载器,添加几个 BeanPostProcessor,手动注册几个特殊的 bean
  8. prepareBeanFactory(beanFactory);
  9. try {
  10. // 扩展点
  11. postProcessBeanFactory(beanFactory);
  12. // 调用 BeanFactoryPostProcessor 各个实现类的 postProcessBeanFactory(factory) 方法
  13. invokeBeanFactoryPostProcessors(beanFactory);
  14. // 注册 BeanPostProcessor 的实现类
  15. registerBeanPostProcessors(beanFactory);
  16. // 初始化MessageSource
  17. initMessageSource();
  18. // 初始化事件广播器
  19. initApplicationEventMulticaster();
  20. // 扩展点
  21. onRefresh();
  22. // 注册事件监听器
  23. registerListeners();
  24. // 初始化所有的 singleton beans
  25. finishBeanFactoryInitialization(beanFactory);
  26. // 广播事件
  27. finishRefresh();
  28. }
  29. catch (BeansException ex) {
  30. if (logger.isWarnEnabled()) {
  31. logger.warn("Exception encountered during context initialization - " +
  32. "cancelling refresh attempt: " + ex);
  33. }
  34. // 销毁已经初始化的的Bean
  35. destroyBeans();
  36. // 设置 'active' 状态
  37. cancelRefresh(ex);
  38. throw ex;
  39. }
  40. finally {
  41. // 清除缓存
  42. resetCommonCaches();
  43. }
  44. }
  45. }

总结

至此,本文到此结束。鉴于XML方式比较简单、通俗易懂,所以本文基于XML的方式大致介绍了SpringIOC的启动流程、稍微深入的讲解了Bean容器的创建以及Bean的初始化过程。这也是作者第一次阅读开源框架的源码,如文章有错误之处还请您费心指出。

鉴于现在比较流行SpringBoot和SpringCloud,下篇文章将会从基于注解的方向分析SpringIOC