title: 【学习之路】SpringIoC源码简单解析
draft: true
tags:


创建Spring HelloWrold

  1. public class IocTest {
  2. public static void main(String[] args) {
  3. // 在这行代码上上打上断点
  4. ApplicationContext ioc = new ClassPathXmlApplicationContext("conf/ioc.xml");
  5. Object person = ioc.getBean("person");
  6. System.out.println(person);
  7. }
  8. }

创建Person实体类

  1. @AllArgsConstructor
  2. @ToString
  3. @Data
  4. public class Person {
  5. private String lastName;
  6. private Integer age;
  7. private String sex;
  8. public Person(){
  9. System.out.println("person创建了");
  10. }
  11. }

创建IoC配置文件

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
  5. <bean id="person" class="com.zixuan.my_spring.Person">
  6. <property name="lastName" value="张三"></property>
  7. <property name="age" value="18"></property>
  8. <property name="sex" value="男"></property>
  9. </bean>
  10. <bean id="person2" class="com.zixuan.my_spring.Person">
  11. <property name="lastName" value="李四"></property>
  12. <property name="age" value="30"></property>
  13. <property name="sex" value="男"></property>
  14. </bean>
  15. <bean id="person3" class="com.zixuan.my_spring.Person">
  16. <property name="lastName" value="王五"></property>
  17. <property name="age" value="29"></property>
  18. <property name="sex" value="男"></property>
  19. </bean>
  20. <bean id="person4" class="com.zixuan.my_spring.Person">
  21. </bean>
  22. </beans>

源码解析

运行主方法,这时进入了ClassPathXmlApplicationContext这个类的构造器

  1. public ClassPathXmlApplicationContext(String configLocation) throws BeansException {
  2. // 点击this进入当前方法
  3. this(new String[] {configLocation}, true, null);
  4. }

基本上所有的构造器都是调用this

SpringIoC源码 - 图1

点击this后进入当前方法

  1. public ClassPathXmlApplicationContext(String[] configLocations, boolean refresh, ApplicationContext parent)
  2. throws BeansException {
  3. // 可以试着放行方法,并且看控制台是否有打印
  4. super(parent);
  5. setConfigLocations(configLocations);
  6. if (refresh) {
  7. // 如果放行此方法,那么控制台就会打印所有创建Bean的信息
  8. refresh();
  9. }
  10. }

DeBug模式下按F7进入该方法,这时跳转到了AbstractApplicationContext这个类中

  1. @Override
  2. public void refresh() throws BeansException, IllegalStateException {
  3. // 同步锁保证多线程状态下IoC线程只会创建一次
  4. synchronized (this.startupShutdownMonitor) {
  5. // 准备容器刷新
  6. // Prepare this context for refreshing.
  7. prepareRefresh();
  8. // 创建一个ConfigurableListableBeanFactory打开当前类的继承树是BeanFactory的实现接口
  9. // Tell the subclass to refresh the internal bean factory.
  10. // 当前方法用于解析SpringIoC的XML文件,将XML文件中的Bean保存
  11. ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
  12. // Prepare the bean factory for use in this context.
  13. prepareBeanFactory(beanFactory);
  14. try {
  15. // Allows post-processing of the bean factory in context subclasses.
  16. postProcessBeanFactory(beanFactory);
  17. // Spring初始化自己所需的组件
  18. // Invoke factory processors registered as beans in the context.
  19. invokeBeanFactoryPostProcessors(beanFactory);
  20. // Register bean processors that intercept bean creation.
  21. registerBeanPostProcessors(beanFactory);
  22. // Spring国际化功能
  23. // Initialize message source for this context.
  24. initMessageSource();
  25. // Initialize event multicaster for this context.
  26. initApplicationEventMulticaster();
  27. // 留给子类的方法,方法内部是一个空方法
  28. // Initialize other special beans in specific context subclasses.
  29. onRefresh();
  30. // Check for listener beans and register them.
  31. registerListeners();
  32. // 初始化所有没有懒加载的单列Bean,所有Bean加载内容在这个方法进行创建,进入当前方法查看Bean创建过程
  33. // Instantiate all remaining (non-lazy-init) singletons.
  34. finishBeanFactoryInitialization(beanFactory);
  35. // Last step: publish corresponding event.
  36. finishRefresh();
  37. }
  38. catch (BeansException ex) {
  39. if (logger.isWarnEnabled()) {
  40. logger.warn("Exception encountered during context initialization - " +
  41. "cancelling refresh attempt: " + ex);
  42. }
  43. // Destroy already created singletons to avoid dangling resources.
  44. destroyBeans();
  45. // Reset 'active' flag.
  46. cancelRefresh(ex);
  47. // Propagate exception to caller.
  48. throw ex;
  49. }
  50. finally {
  51. // Reset common introspection caches in Spring's core, since we
  52. // might not ever need metadata for singleton beans anymore...
  53. resetCommonCaches();
  54. }
  55. }
  56. }

进入finishBeanFactoryInitialization(beanFactory);

  1. protected void finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory) {
  2. // Initialize conversion service for this context.
  3. if (beanFactory.containsBean(CONVERSION_SERVICE_BEAN_NAME) &&
  4. beanFactory.isTypeMatch(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class)) {
  5. beanFactory.setConversionService(
  6. beanFactory.getBean(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class));
  7. }
  8. // Register a default embedded value resolver if no bean post-processor
  9. // (such as a PropertyPlaceholderConfigurer bean) registered any before:
  10. // at this point, primarily for resolution in annotation attribute values.
  11. if (!beanFactory.hasEmbeddedValueResolver()) {
  12. beanFactory.addEmbeddedValueResolver(new StringValueResolver() {
  13. @Override
  14. public String resolveStringValue(String strVal) {
  15. return getEnvironment().resolvePlaceholders(strVal);
  16. }
  17. });
  18. }
  19. // Initialize LoadTimeWeaverAware beans early to allow for registering their transformers early.
  20. String[] weaverAwareNames = beanFactory.getBeanNamesForType(LoadTimeWeaverAware.class, false, false);
  21. for (String weaverAwareName : weaverAwareNames) {
  22. getBean(weaverAwareName);
  23. }
  24. // Stop using the temporary ClassLoader for type matching.
  25. beanFactory.setTempClassLoader(null);
  26. // Allow for caching all bean definition metadata, not expecting further changes.
  27. beanFactory.freezeConfiguration();
  28. // 初始化所有的单列Bean,再次进入当前方法查看Bean创建过程
  29. // Instantiate all remaining (non-lazy-init) singletons.
  30. beanFactory.preInstantiateSingletons();
  31. }

再次进入beanFactory.preInstantiateSingletons();又跳转到了DefaultListableBeanFactory类中

  1. @Override
  2. public void preInstantiateSingletons() throws BeansException {
  3. if (logger.isDebugEnabled()) {
  4. logger.debug("Pre-instantiating singletons in " + this);
  5. }
  6. // Iterate over a copy to allow for init methods which in turn register new bean definitions.
  7. // While this may not be part of the regular factory bootstrap, it does otherwise work fine.
  8. // 拿到所有要创建Bean的名称并加锁
  9. List<String> beanNames = new ArrayList<String>(this.beanDefinitionNames);
  10. // 通过增强for循环依次创建Bean
  11. // Trigger initialization of all non-lazy singleton beans...
  12. for (String beanName : beanNames) {
  13. // 获取Bean的详细信息,判断当前Bean是否是抽象,是否是单列,是否是懒加载
  14. RootBeanDefinition bd = getMergedLocalBeanDefinition(beanName);
  15. if (!bd.isAbstract() && bd.isSingleton() && !bd.isLazyInit()) {
  16. if (isFactoryBean(beanName)) { // 判断当前Bean是否是工厂Bean,是否实现了FactoryBean接口的Bean
  17. final FactoryBean<?> factory = (FactoryBean<?>) getBean(FACTORY_BEAN_PREFIX + beanName);
  18. boolean isEagerInit;
  19. if (System.getSecurityManager() != null && factory instanceof SmartFactoryBean) {
  20. isEagerInit = AccessController.doPrivileged(new PrivilegedAction<Boolean>() {
  21. @Override
  22. public Boolean run() {
  23. return ((SmartFactoryBean<?>) factory).isEagerInit();
  24. }
  25. }, getAccessControlContext());
  26. }
  27. else {
  28. isEagerInit = (factory instanceof SmartFactoryBean &&
  29. ((SmartFactoryBean<?>) factory).isEagerInit());
  30. }
  31. if (isEagerInit) {
  32. getBean(beanName);
  33. }
  34. }
  35. else {
  36. // 当前方法如果放行就会创建一个Bean,这个方法中又Bean的具体实现
  37. getBean(beanName);
  38. }
  39. }
  40. }
  41. // Trigger post-initialization callback for all applicable beans...
  42. for (String beanName : beanNames) {
  43. Object singletonInstance = getSingleton(beanName);
  44. if (singletonInstance instanceof SmartInitializingSingleton) {
  45. final SmartInitializingSingleton smartSingleton = (SmartInitializingSingleton) singletonInstance;
  46. if (System.getSecurityManager() != null) {
  47. AccessController.doPrivileged(new PrivilegedAction<Object>() {
  48. @Override
  49. public Object run() {
  50. smartSingleton.afterSingletonsInstantiated();
  51. return null;
  52. }
  53. }, getAccessControlContext());
  54. }
  55. else {
  56. smartSingleton.afterSingletonsInstantiated();
  57. }
  58. }
  59. }
  60. }

进入getBean(beanName)跳转到AbstractBeanFactory类中

  1. public Object getBean(String name) throws BeansException {
  2. return this.doGetBean(name, (Class)null, (Object[])null, false);
  3. }

再次进入doGetBean

  1. protected <T> T doGetBean(String name, Class<T> requiredType, final Object[] args, boolean typeCheckOnly) throws BeansException {
  2. final String beanName = this.transformedBeanName(name);
  3. // 从已经注册的单实例Bean中检查是否有没有当前Bean
  4. Object sharedInstance = this.getSingleton(beanName);
  5. Object bean;
  6. if (sharedInstance != null && args == null) {
  7. if (this.logger.isDebugEnabled()) {
  8. if (this.isSingletonCurrentlyInCreation(beanName)) {
  9. this.logger.debug("Returning eagerly cached instance of singleton bean '" + beanName + "' that is not fully initialized yet - a consequence of a circular reference");
  10. } else {
  11. this.logger.debug("Returning cached instance of singleton bean '" + beanName + "'");
  12. }
  13. }
  14. bean = this.getObjectForBeanInstance(sharedInstance, name, beanName, (RootBeanDefinition)null);
  15. } else {
  16. if (this.isPrototypeCurrentlyInCreation(beanName)) {
  17. throw new BeanCurrentlyInCreationException(beanName);
  18. }
  19. BeanFactory parentBeanFactory = this.getParentBeanFactory();
  20. if (parentBeanFactory != null && !this.containsBeanDefinition(beanName)) {
  21. String nameToLookup = this.originalBeanName(name);
  22. if (args != null) {
  23. return parentBeanFactory.getBean(nameToLookup, args);
  24. }
  25. return parentBeanFactory.getBean(nameToLookup, requiredType);
  26. }
  27. // 标记Bean已经创建
  28. if (!typeCheckOnly) {
  29. this.markBeanAsCreated(beanName);
  30. }
  31. try {
  32. // 获取Bean的定义信息
  33. final RootBeanDefinition mbd = this.getMergedLocalBeanDefinition(beanName);
  34. this.checkMergedBeanDefinition(mbd, beanName, args);
  35. // 拿到创建当前需要创建的Bean,depends-on属性,如果有就循环创建
  36. String[] dependsOn = mbd.getDependsOn();
  37. String[] var11;
  38. if (dependsOn != null) {
  39. var11 = dependsOn;
  40. int var12 = dependsOn.length;
  41. for(int var13 = 0; var13 < var12; ++var13) {
  42. String dep = var11[var13];
  43. if (this.isDependent(beanName, dep)) {
  44. throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Circular depends-on relationship between '" + beanName + "' and '" + dep + "'");
  45. }
  46. this.registerDependentBean(dep, beanName);
  47. try {
  48. this.getBean(dep);
  49. } catch (NoSuchBeanDefinitionException var24) {
  50. throw new BeanCreationException(mbd.getResourceDescription(), beanName, "'" + beanName + "' depends on missing bean '" + dep + "'", var24);
  51. }
  52. }
  53. }
  54. // 如果mbd是单列的就创建Bean实列
  55. if (mbd.isSingleton()) {
  56. // 获取当前Bean,进入当前方法
  57. sharedInstance = this.getSingleton(beanName, new ObjectFactory<Object>() {
  58. public Object getObject() throws BeansException {
  59. try {
  60. // 创建Bean过程
  61. return AbstractBeanFactory.this.createBean(beanName, mbd, args);
  62. } catch (BeansException var2) {
  63. AbstractBeanFactory.this.destroySingleton(beanName);
  64. throw var2;
  65. }
  66. }
  67. });
  68. bean = this.getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
  69. } else if (mbd.isPrototype()) {
  70. var11 = null;
  71. Object prototypeInstance;
  72. try {
  73. this.beforePrototypeCreation(beanName);
  74. prototypeInstance = this.createBean(beanName, mbd, args);
  75. } finally {
  76. this.afterPrototypeCreation(beanName);
  77. }
  78. bean = this.getObjectForBeanInstance(prototypeInstance, name, beanName, mbd);
  79. } else {
  80. String scopeName = mbd.getScope();
  81. Scope scope = (Scope)this.scopes.get(scopeName);
  82. if (scope == null) {
  83. throw new IllegalStateException("No Scope registered for scope name '" + scopeName + "'");
  84. }
  85. try {
  86. Object scopedInstance = scope.get(beanName, new ObjectFactory<Object>() {
  87. public Object getObject() throws BeansException {
  88. AbstractBeanFactory.this.beforePrototypeCreation(beanName);
  89. Object var1;
  90. try {
  91. var1 = AbstractBeanFactory.this.createBean(beanName, mbd, args);
  92. } finally {
  93. AbstractBeanFactory.this.afterPrototypeCreation(beanName);
  94. }
  95. return var1;
  96. }
  97. });
  98. bean = this.getObjectForBeanInstance(scopedInstance, name, beanName, mbd);
  99. } catch (IllegalStateException var23) {
  100. 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", var23);
  101. }
  102. }
  103. } catch (BeansException var26) {
  104. this.cleanupAfterBeanCreationFailure(beanName);
  105. throw var26;
  106. }
  107. }
  108. if (requiredType != null && bean != null && !requiredType.isInstance(bean)) {
  109. try {
  110. return this.getTypeConverter().convertIfNecessary(bean, requiredType);
  111. } catch (TypeMismatchException var25) {
  112. if (this.logger.isDebugEnabled()) {
  113. this.logger.debug("Failed to convert bean '" + name + "' to required type '" + ClassUtils.getQualifiedName(requiredType) + "'", var25);
  114. }
  115. throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass());
  116. }
  117. } else {
  118. return bean;
  119. }
  120. }

进入到getSingleton(beanName, new ObjectFactory<Object>())

  1. public Object getSingleton(String beanName, ObjectFactory<?> singletonFactory) {
  2. Assert.notNull(beanName, "'beanName' must not be null");
  3. synchronized (this.singletonObjects) {
  4. // 先从singletonObjects中通过bean的名称获取bean对象,
  5. // singletonObjects是当前类定义的一个Map,也就是Bean存储在一个Map中
  6. Object singletonObject = this.singletonObjects.get(beanName);
  7. if (singletonObject == null) {
  8. if (this.singletonsCurrentlyInDestruction) {
  9. throw new BeanCreationNotAllowedException(beanName,
  10. "Singleton bean creation not allowed while singletons of this factory are in destruction " +
  11. "(Do not request a bean from a BeanFactory in a destroy method implementation!)");
  12. }
  13. if (logger.isDebugEnabled()) {
  14. logger.debug("Creating shared instance of singleton bean '" + beanName + "'");
  15. }
  16. beforeSingletonCreation(beanName);
  17. boolean newSingleton = false;
  18. boolean recordSuppressedExceptions = (this.suppressedExceptions == null);
  19. if (recordSuppressedExceptions) {
  20. this.suppressedExceptions = new LinkedHashSet<Exception>();
  21. }
  22. try {
  23. // 通过反射创建Bean对象
  24. singletonObject = singletonFactory.getObject();
  25. newSingleton = true;
  26. }
  27. catch (IllegalStateException ex) {
  28. // Has the singleton object implicitly appeared in the meantime ->
  29. // if yes, proceed with it since the exception indicates that state.
  30. singletonObject = this.singletonObjects.get(beanName);
  31. if (singletonObject == null) {
  32. throw ex;
  33. }
  34. }
  35. catch (BeanCreationException ex) {
  36. if (recordSuppressedExceptions) {
  37. for (Exception suppressedException : this.suppressedExceptions) {
  38. ex.addRelatedCause(suppressedException);
  39. }
  40. }
  41. throw ex;
  42. }
  43. finally {
  44. if (recordSuppressedExceptions) {
  45. this.suppressedExceptions = null;
  46. }
  47. afterSingletonCreation(beanName);
  48. }
  49. if (newSingleton) {
  50. // 添加单实例Bean存储到singletonObject中
  51. addSingleton(beanName, singletonObject);
  52. }
  53. }
  54. return (singletonObject != NULL_OBJECT ? singletonObject : null);
  55. }
  56. }

singletonObject是一个Map,当前bean的名字为key,value为当前存储的Bean对象

SpringIoC源码 - 图2

进入addSingleton(beanName, singletonObject);

  1. protected void addSingleton(String beanName, Object singletonObject) {
  2. synchronized (this.singletonObjects) {
  3. // 将Bean对象加入到Map中
  4. this.singletonObjects.put(beanName, (singletonObject != null ? singletonObject : NULL_OBJECT));
  5. this.singletonFactories.remove(beanName);
  6. this.earlySingletonObjects.remove(beanName);
  7. this.registeredSingletons.add(beanName);
  8. }
  9. }