Spring启动流程

  • 首先创建一个测试案例,导入Spring相关依赖:

    1
    2
    3
    4
    5
    <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context</artifactId>
    <version>5.2.5.RELEASE</version>
    </dependency>
  • 注解版测试用例如下:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    public class User {
    private String name;
    private String password;

    public String getName() {
    return name;
    }

    public void setName(String name) {
    this.name = name;
    }

    public String getPassword() {
    return password;
    }

    public void setPassword(String password) {
    this.password = password;
    }

    public User() {
    System.out.println("执行了User的构造器");
    }

    public User(String name, String password) {
    this.name = name;
    this.password = password;
    System.out.println("有参构造器");
    }

    @Override
    public String toString() {
    return "User{" +
    "name='" + name + '\'' +
    ", password='" + password + '\'' +
    '}';
    }
    }
    1
    2
    3
    4
    5
    6
    7
    @Configuration
    public class MainConfig {
    @Bean
    public User user(){
    return new User();
    }
    }
    1
    2
    3
    4
    5
    6
    7
    public class MainTest {
    public static void main(String[] args) {
    AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(MainConfig.class);
    User user = applicationContext.getBean(User.class);
    System.out.println(user);
    }
    }
  • xml版测试用例如下:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

    <bean id="user" class="com.example.annotation.test.User">
    <property name="name" value="zhangsan"></property>
    <property name="password" value="123456"></property>
    </bean>

    </beans>
    1
    2
    3
    4
    5
    6
    7
    public class MainTest {
    public static void main(String[] args) {
    ApplicationContext applicationContext = new ClassPathXmlApplicationContext("beans.xml");
    User user = applicationContext.getBean(User.class);
    System.out.println(user);
    }
    }
  • AnnotationConfigApplicationContext(IOC容器)的有关继承树如图:

  • DefaultListableBeanFactory(Bean工厂)的有关继承树如图:

  • Spring中后置处理器的作用:

  • Spring中创建对象包括:

  • Spring中Aware接口的作用:

    • 当Spring容器创建的bean对象在进行具体操作的时候,如果需要容器的其他对象,此时可以将对象实现Aware接口,来满足当前的需要。
  • Spring中提供的各种接口:

  • 打断点进入new ClassPathXmlApplicationContext(“beans.xml”)构造器:

    1
    2
    3
    public ClassPathXmlApplicationContext(String configLocation) throws BeansException {
    this(new String[] {configLocation}, true, null);
    }
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    public ClassPathXmlApplicationContext(
    String[] configLocations, boolean refresh, @Nullable ApplicationContext parent)
    throws BeansException {
    //调用父类构造方法,进行相关的对象创建等操作
    super(parent);
    //设置应用程序上下文的配置路径
    setConfigLocations(configLocations);
    if (refresh) {
    refresh();
    }
    }
    • ①调用父类构造方法,进行相关的对象创建等操作。

      1
      2
      3
      public AbstractXmlApplicationContext(@Nullable ApplicationContext parent) {
      super(parent);
      }
      1
      2
      3
      public AbstractRefreshableConfigApplicationContext(@Nullable ApplicationContext parent) {
      super(parent);
      }
      1
      2
      3
      public AbstractRefreshableApplicationContext(@Nullable ApplicationContext parent) {
      super(parent);
      }
      1
      2
      3
      4
      5
      public AbstractApplicationContext(@Nullable ApplicationContext parent) {
      this();
      // 这里parent即父容器为null
      setParent(parent);
      }
      1
      2
      3
      4
      public AbstractApplicationContext() {
      //创建资源模式处理器
      this.resourcePatternResolver = getResourcePatternResolver();
      }
      1
      2
      3
      4
      protected ResourcePatternResolver getResourcePatternResolver() {
      //创建一个资源模式解析器(其实就是用来解析xml配置文件)
      return new PathMatchingResourcePatternResolver(this);
      }
    • ②设置应用程序上下文的配置路径。

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      //AbstractRefreshableConfigApplicationContext类中,此方法将解析后的配置文件路径放进AbstractRefreshableConfigApplicationContext类的成员变量String[] configLocations数组中
      public void setConfigLocations(@Nullable String... locations) {
      if (locations != null) {
      Assert.noNullElements(locations, "Config locations must not be null");
      this.configLocations = new String[locations.length];
      for (int i = 0; i < locations.length; i++) {
      //解析给定路径,如果传进来的配置文件名为spring-${username}.xml等形式时需要被解析
      this.configLocations[i] = resolvePath(locations[i]).trim();
      }
      }
      else {
      this.configLocations = null;
      }
      }
      1
      2
      3
      protected String resolvePath(String path) {
      return getEnvironment().resolveRequiredPlaceholders(path);
      }
      • 分成两步,第一步获取环境变量。

        1
        2
        3
        4
        5
        6
        7
        @Override
        public ConfigurableEnvironment getEnvironment() {
        if (this.environment == null) {
        this.environment = createEnvironment();
        }
        return this.environment;
        }
        1
        2
        3
        4
        protected ConfigurableEnvironment createEnvironment() {
        // StandardEnvironment类里没有显示写构造方法,说明默认是一个无参构造方法,其中会调用父类的构造方法
        return new StandardEnvironment();
        }
        1
        2
        3
        4
        5
        //父类AbstractEnvironment的构造方法
        public AbstractEnvironment() {
        //父类AbstractEnvironment中此方法为空实现,实际交由子类StandardEnvironment来实现
        customizePropertySources(this.propertySources);
        }
        1
        2
        3
        4
        5
        6
        7
        8
        9
        10
        //子类StandardEnvironment实现的customizePropertySources方法
        @Override
        protected void customizePropertySources(MutablePropertySources propertySources) {
        //获取并设置系统的一些默认属性。如运行时的目录、用户名、用户目录、语言、操作系统、操作系统默认编码等等等
        propertySources.addLast(
        new PropertiesPropertySource(SYSTEM_PROPERTIES_PROPERTY_SOURCE_NAME, getSystemProperties()));
        //获取并设置操作系统的环境变量(包括当前用户的环境变量),如path中的环境变量
        propertySources.addLast(
        new SystemEnvironmentPropertySource(SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME, getSystemEnvironment()));
        }
      • 第二步处理一些必需的占位符。

        1
        2
        3
        4
        @Override
        public String resolveRequiredPlaceholders(String text) throws IllegalArgumentException {
        return this.propertyResolver.resolveRequiredPlaceholders(text);
        }
        1
        2
        3
        4
        5
        6
        7
        @Override
        public String resolveRequiredPlaceholders(String text) throws IllegalArgumentException {
        if (this.strictHelper == null) {
        this.strictHelper = createPlaceholderHelper(false);
        }
        return doResolvePlaceholders(text, this.strictHelper);
        }
        1
        2
        3
        private String doResolvePlaceholders(String text, PropertyPlaceholderHelper helper) {
        return helper.replacePlaceholders(text, this::getPropertyAsRawString);
        }
        1
        2
        3
        4
        public String replacePlaceholders(String value, PlaceholderResolver placeholderResolver) {
        Assert.notNull(value, "'value' must not be null");
        return parseStringValue(value, placeholderResolver, null);
        }
        1
        2
        3
        4
        5
        6
        7
        8
        9
        10
        11
        12
        13
        14
        15
        16
        17
        18
        19
        20
        21
        22
        23
        24
        25
        26
        27
        28
        29
        30
        31
        32
        33
        34
        35
        36
        37
        38
        39
        40
        41
        42
        43
        44
        45
        46
        47
        48
        49
        50
        51
        52
        53
        54
        55
        56
        57
        58
        59
        60
        61
        62
        63
        64
        65
        66
        67
        //PropertyPlaceholderHelper类中
        protected String parseStringValue(
        String value, PlaceholderResolver placeholderResolver, @Nullable Set<String> visitedPlaceholders) {
        //判断xml配置文件名中是否包含${
        int startIndex = value.indexOf(this.placeholderPrefix);
        if (startIndex == -1) {
        return value;
        }

        StringBuilder result = new StringBuilder(value);
        while (startIndex != -1) {
        int endIndex = findPlaceholderEndIndex(result, startIndex);
        if (endIndex != -1) {
        String placeholder = result.substring(startIndex + this.placeholderPrefix.length(), endIndex);
        String originalPlaceholder = placeholder;
        if (visitedPlaceholders == null) {
        visitedPlaceholders = new HashSet<>(4);
        }
        if (!visitedPlaceholders.add(originalPlaceholder)) {
        throw new IllegalArgumentException(
        "Circular placeholder reference '" + originalPlaceholder + "' in property definitions");
        }
        // Recursive invocation, parsing placeholders contained in the placeholder key.
        //递归调用,解析占位符键中包含的占位符
        placeholder = parseStringValue(placeholder, placeholderResolver, visitedPlaceholders);
        // Now obtain the value for the fully resolved key...
        //现在获取完全解析键的值,如果配置文件名为spring-${username}.xml,那么返回的propVal就是系统变量中username的值
        String propVal = placeholderResolver.resolvePlaceholder(placeholder);
        if (propVal == null && this.valueSeparator != null) {
        int separatorIndex = placeholder.indexOf(this.valueSeparator);
        if (separatorIndex != -1) {
        String actualPlaceholder = placeholder.substring(0, separatorIndex);
        String defaultValue = placeholder.substring(separatorIndex + this.valueSeparator.length());
        propVal = placeholderResolver.resolvePlaceholder(actualPlaceholder);
        if (propVal == null) {
        propVal = defaultValue;
        }
        }
        }
        if (propVal != null) {
        // Recursive invocation, parsing placeholders contained in the
        // previously resolved placeholder value.
        //递归调用,解析包含在先前解析的占位符值中的占位符
        propVal = parseStringValue(propVal, placeholderResolver, visitedPlaceholders);
        //文件名替换
        result.replace(startIndex, endIndex + this.placeholderSuffix.length(), propVal);
        if (logger.isTraceEnabled()) {
        logger.trace("Resolved placeholder '" + placeholder + "'");
        }
        startIndex = result.indexOf(this.placeholderPrefix, startIndex + propVal.length());
        }
        else if (this.ignoreUnresolvablePlaceholders) {
        // Proceed with unprocessed value.
        startIndex = result.indexOf(this.placeholderPrefix, endIndex + this.placeholderSuffix.length());
        }
        else {
        throw new IllegalArgumentException("Could not resolve placeholder '" +
        placeholder + "'" + " in value \"" + value + "\"");
        }
        visitedPlaceholders.remove(originalPlaceholder);
        }
        else {
        startIndex = -1;
        }
        }
        return result.toString();
        }
        1
        2
        3
        4
        5
        6
        //placeholderResolver.resolvePlaceholder(placeholder)方法中会调用PropertySourcesPropertyResolver类中的getPropertyAsRawString()方法
        @Override
        @Nullable
        protected String getPropertyAsRawString(String key) {
        return getProperty(key, String.class, false);
        }
        1
        2
        3
        4
        5
        6
        7
        8
        9
        10
        11
        12
        13
        14
        15
        16
        17
        18
        19
        20
        21
        22
        23
        @Nullable
        protected <T> T getProperty(String key, Class<T> targetValueType, boolean resolveNestedPlaceholders) {
        if (this.propertySources != null) {
        for (PropertySource<?> propertySource : this.propertySources) {
        if (logger.isTraceEnabled()) {
        logger.trace("Searching for key '" + key + "' in PropertySource '" +
        propertySource.getName() + "'");
        }
        Object value = propertySource.getProperty(key);
        if (value != null) {
        if (resolveNestedPlaceholders && value instanceof String) {
        value = resolveNestedPlaceholders((String) value);
        }
        logKeyFound(key, propertySource, value);
        return convertValueIfNecessary(value, targetValueType);
        }
        }
        }
        if (logger.isTraceEnabled()) {
        logger.trace("Could not find key '" + key + "' in any property source");
        }
        return null;
        }
    • ③进入AbstractApplicationContext类的refresh()方法,处理逻辑和注解版的类似,后面详细介绍。

  • 打断点进入new AnnotationConfigApplicationContext(MainConfig.class)构造器:

    1
    2
    3
    4
    5
    6
    7
    8
    public AnnotationConfigApplicationContext(Class<?>... componentClasses) {
    //初始化bean读取器和扫描器
    this();
    //注册bean配置类
    register(componentClasses);
    //刷新上下文
    refresh();
    }
    • ①进入this()调用的是无参构造器:

      1
      2
      3
      4
      5
      6
      public AnnotationConfigApplicationContext() {
      //在IOC容器中初始化一个注解bean读取器AnnotatedBeanDefinitionReader
      this.reader = new AnnotatedBeanDefinitionReader(this);
      //在IOC容器中初始化一个按类路径扫描注解bean的扫描器
      this.scanner = new ClassPathBeanDefinitionScanner(this);
      }
    • ②接着进入AnnotationConfigApplicationContext.register(componentClasses)通过AnnotatedBeanDefinitionReader的register方法实现注解bean的读取,register方法重点完成了bean配置类本身的解析和注册,处理过程可以分为以下几个步骤:

      • ①根据bean配置类,使用BeanDefinition解析Bean的定义信息,主要是一些注解信息。
      • ②Bean作用域的处理,默认缺少@Scope注解,解析成单例。
      • ③借助AnnotationConfigUtils工具类解析通用注解。
      • ④将bean定义信息已beanname,beandifine键值对的形式注册到ioc容器中。
      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      16
      17
      18
      19
      20
      21
      22
      23
      24
      25
      26
      27
      28
      29
      30
      31
      32
      33
      34
      35
      36
      37
      38
      39
      40
      41
      42
      43
      44
      45
      46
      47
      48
      49
      50
      51
      52
      53
      54
      55
      56
      57
      58
      59
      60
      61
      62
      63
      64
      65
      66
      public void register(Class<?>... componentClasses) {
      Assert.notEmpty(componentClasses, "At least one component class must be specified");
      //调用AnnotatedBeanDefinitionReader的register方法
      this.reader.register(componentClasses);
      }

      //按指定bean配置类读取bean
      public void register(Class<?>... componentClasses) {
      for (Class<?> componentClass : componentClasses) {
      registerBean(componentClass);
      }
      }

      public void registerBean(Class<?> beanClass) {
      doRegisterBean(beanClass, null, null, null, null);
      }

      private <T> void doRegisterBean(Class<T> beanClass, @Nullable String name,
      @Nullable Class<? extends Annotation>[] qualifiers, @Nullable Supplier<T> supplier,
      @Nullable BeanDefinitionCustomizer[] customizers) {
      //将Bean配置类信息转成容器中AnnotatedGenericBeanDefinition数据结构,下面的getMetadata可以获取到该bean上的注解信息。
      AnnotatedGenericBeanDefinition abd = new AnnotatedGenericBeanDefinition(beanClass);
      //@Conditional装配条件判断是否需要跳过注册
      if (this.conditionEvaluator.shouldSkip(abd.getMetadata())) {
      return;
      }
      // 回调用的
      abd.setInstanceSupplier(supplier);
      //解析bean作用域(单例或者原型),如果有@Scope注解,则解析@Scope,没有则默认为singleton。
      ScopeMetadata scopeMetadata = this.scopeMetadataResolver.resolveScopeMetadata(abd);
      //作用域写回AnnotatedGenericBeanDefinition数据结构, abd中缺损的情况下为空,将默认值singleton重新赋值到abd。
      abd.setScope(scopeMetadata.getScopeName());
      //生成bean配置类beanName
      String beanName = (name != null ? name : this.beanNameGenerator.generateBeanName(abd, this.registry));
      //通用注解解析到abd结构中,主要是处理Lazy, primary DependsOn, Role ,Description这五个注解。
      AnnotationConfigUtils.processCommonDefinitionAnnotations(abd);
      if (qualifiers != null) {
      for (Class<? extends Annotation> qualifier : qualifiers) {
      //如果配置@Primary注解,则设置当前Bean为自动装配autowire时首选bean。
      if (Primary.class == qualifier) {
      abd.setPrimary(true);
      }
      //设置当前bean为延迟加载。
      else if (Lazy.class == qualifier) {
      abd.setLazyInit(true);
      }
      //其他注解,则添加到abd结构中。
      else {
      abd.addQualifier(new AutowireCandidateQualifier(qualifier));
      }
      }
      }
      //自定义bean注册,通常用在applicationContext创建后,手动向容器中一lambda表达式的方式注册bean。
      if (customizers != null) {
      for (BeanDefinitionCustomizer customizer : customizers) {
      //自定义bean添加到BeanDefinitionCustomizer。
      customizer.customize(abd);
      }
      }
      //定义一个BeanDefinitionHolder,就是beanName和BeanDefinition的映射
      BeanDefinitionHolder definitionHolder = new BeanDefinitionHolder(abd, beanName);
      //是否有代理
      definitionHolder = AnnotationConfigUtils.applyScopedProxyMode(scopeMetadata, definitionHolder, this.registry);
      //内部通过DefaultListableBeanFactory.registerBeanDefinition(String beanName, BeanDefinition beanDefinition)按名称将bean定义信息注册到容器中,实际上DefaultListableBeanFactory内部维护一个Map<String, BeanDefinition>类型变量beanDefinitionMap,用于保存注bean定义信息(beanname 和 beandefine映射)。
      BeanDefinitionReaderUtils.registerBeanDefinition(definitionHolder, this.registry);
      }
    • ③接着进入refresh()方法,其在父类在AbstractApplicationContext中实现,作用是加载或者刷新当前的配置信息,如果已经存在spring容器,则先销毁之前的容器,重新创建spring容器,载入bean定义,完成容器初始化工作。

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      16
      17
      18
      19
      20
      21
      22
      23
      24
      25
      26
      27
      28
      29
      30
      31
      32
      33
      34
      35
      36
      37
      38
      39
      40
      41
      42
      43
      44
      45
      46
      47
      48
      49
      50
      51
      52
      53
      54
      55
      56
      57
      58
      59
      60
      61
      62
      63
      64
      65
      66
      67
      68
      69
      70
      71
      72
      73
      74
      75
      76
      77
      78
      79
      80
      81
      82
      83
      84
      85
      86
      87
      88
      89
      90
      91
      92
      93
      94
      95
      96
      97
      98
      99
      100
      101
      102
      103
      104
      105
      106
      107
      108
      109
      110
      111
      112
      113
      114
      @Override
      public void refresh() throws BeansException, IllegalStateException {
      synchronized (this.startupShutdownMonitor) {
      // Prepare this context for refreshing.
      //刷新上下文前的预处理。
      prepareRefresh();

      // Tell the subclass to refresh the internal bean factory.
      //获取刷新后的内部Bean工厂。
      /**
      * 初始化BeanFactory,解析xml格式的配置文件
      * xml格式的配置,是在这个方法中扫描到beanDefinitionMap中的
      * 在org.springframework.web.context.support.XmlWebApplicationContext#loadBeanDefinitions(org.springframework.beans.factory.support.DefaultListableBeanFactory)中会创建一个XmlBeanDefinitionReader来解析xml文件
      * 会把bean.xml解析成一个InputStream,然后再解析成document格式
      * 按照document格式解析,从root节点进行解析,判断root节点是bean?还是beans?还是import等,如果是bean
      * 就把解析到的信息包装成beanDefinitionHolder,然后调用DefaultListablebeanFactory的注册方法将bean放到beanDefinitionMap中
      */
      ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();

      // Prepare the bean factory for use in this context.
      //BeanFactory的预准备工作。
      //准备工厂,给BeanFactory设置属性、添加后置处理器等
      prepareBeanFactory(beanFactory);

      try {
      // Allows post-processing of the bean factory in context subclasses.
      //空方法,用于在容器的子类中扩展。
      postProcessBeanFactory(beanFactory);

      // Invoke factory processors registered as beans in the context.
      //执行BeanFactoryPostProcessor的方法,BeanFactory的后置处理器,在BeanFactory标准初始化之后执行的。
      /**
      * TODO
      * 完成对bean的扫描,将class变成beanDefinition,并将beanDefinition存到map中
      *
      * 该方法在spring的环境中执行已经被注册的factory processors;
      * 执行自定义的processBeanFactory
      *
      * 在这个方法中,注入bean,分为了三种
      * 一、普通bean:@Component注解的bean
      * spring 自己的类,不借助spring扫描,会直接放到beanDefinitionMap
      *
      * 1.获取到所有的beanFactoryPostProcessor
      * 2.执行 bean后置处理器的postProcessBeanFactory(configurationClassPostProcessor),该方法会把beanFactory作为入参传到方法里面
      * 3.从beanFactory中获取到所有的beanName 打断点看一下 org.springframework.context.annotation .ConfigurationClassPostProcessor#processConfigBeanDefinitions
      *
      * 4.然后将所有的bean包装成beanDefinitionHolder,在后面又根据beanName和bean的metadata包装成了ConfigurationClass
      * 5.把所有包含@ComponentScan的类取出来,遍历每一个componentScan,调用 ClassPathBeanDefinitionScanner.doScan(basePackages)方法
      * 6.在doScan方法中,会遍历basePackages,因为一个ComponentScan中可以配置多个要扫描的包
      * 7.获取每个包下面的 *.class文件,registerBeanDefinition(definitionHolder, this.registry); 这个方法底层就是调用org.springframework.beans.factory.support.DefaultListableBeanFactory#registerBeanDefinition方法 把当前bean put到beanDefinitionMap中
      *
      * 二、是通过@Import注解注入的bean
      * ImportBeanDefinitionRegistrar
      * ImportSelector
      *
      * 三、@Bean注解
      *
      *
      * spring在把bean注入到beanDefinitionMaps的同时,会将当前beanName添加到一个list中 beanDefinitionNames,这个list和beanDefinitionMap是同时进行添加的,这个list在后面实例化bean的时候有用到,spring是遍历这个list,拿到每个beanName之后,从beanDefinitionMap中取到对应的beanDefinition
      */
      invokeBeanFactoryPostProcessors(beanFactory);

      // Register bean processors that intercept bean creation.
      //注册BeanPostProcessor(Bean的后置处理器),用于拦截bean创建过程。
      registerBeanPostProcessors(beanFactory);

      // Initialize message source for this context.
      //初始化MessageSource组件(做国际化功能;消息绑定,消息解析)。
      initMessageSource();

      // Initialize event multicaster for this context.
      //初始化事件派发器。
      initApplicationEventMulticaster();

      // Initialize other special beans in specific context subclasses.
      //空方法,可以用于子类实现在容器刷新时自定义逻辑。
      onRefresh();

      // Check for listener beans and register them.
      //注册时间监听器,将所有项目里面的ApplicationListener注册到容器中来。
      registerListeners();

      // Instantiate all remaining (non-lazy-init) singletons.
      //初始化所有剩下的单实例bean,单例bean在初始化容器时创建,原型bean在获取时(getbean)时创建。
      finishBeanFactoryInitialization(beanFactory);

      // Last step: publish corresponding event.
      //完成BeanFactory的初始化创建工作,IOC容器就创建完成。
      finishRefresh();
      }

      catch (BeansException ex) {
      if (logger.isWarnEnabled()) {
      logger.warn("Exception encountered during context initialization - " +
      "cancelling refresh attempt: " + ex);
      }

      // Destroy already created singletons to avoid dangling resources.
      destroyBeans();

      // Reset 'active' flag.
      cancelRefresh(ex);

      // Propagate exception to caller.
      throw ex;
      }

      finally {
      // Reset common introspection caches in Spring's core, since we
      // might not ever need metadata for singleton beans anymore...
      resetCommonCaches();
      }
      }
      }
  • 打断点进入AbstractApplicationContext.prepareRefresh()方法,即刷新上下文前的预处理:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    protected void prepareRefresh() {
    // Switch to active.
    //设置容器启动时间
    this.startupDate = System.currentTimeMillis();
    //设置容器关闭状态为false
    this.closed.set(false);
    //设置容器活跃状态为true
    this.active.set(true);
    //日志记录
    if (logger.isDebugEnabled()) {
    if (logger.isTraceEnabled()) {
    logger.trace("Refreshing " + this);
    }
    else {
    logger.debug("Refreshing " + getDisplayName());
    }
    }

    // Initialize any placeholder property sources in the context environment.
    //空方法,留给子类覆盖,初始化属性资源
    initPropertySources();

    // Validate that all properties marked as required are resolvable:
    // see ConfigurablePropertyResolver#setRequiredProperties
    //创建并获取环境对象,验证需要的属性文件是否都已经放入环境中
    getEnvironment().validateRequiredProperties();

    // Store pre-refresh ApplicationListeners...
    //判断刷新前的应用程序监听器集合是否为空,如果为空,则将监听器添加到此集合中
    if (this.earlyApplicationListeners == null) {
    //这里的this.applicationListeners.size()=0,但是在springboot中不为0,实际是一个扩展点
    this.earlyApplicationListeners = new LinkedHashSet<>(this.applicationListeners);
    }
    else {
    // Reset local application listeners to pre-refresh state.
    //如果不等于空,则清空集合元素对象
    this.applicationListeners.clear();
    this.applicationListeners.addAll(this.earlyApplicationListeners);
    }

    // Allow for the collection of early ApplicationEvents,
    // to be published once the multicaster is available...
    //创建刷新前的监听事件集合
    this.earlyApplicationEvents = new LinkedHashSet<>();
    }
    • ①设置容器启动时间。

    • ②设置关闭状态为false。

    • ③设置活跃状态为true。

    • ④调用AbstractApplicationContext.initPropertySources(),即初始化一些属性设置。子类自定义个性化的属性设置方法(即可以自定义一个AnnotationConfigApplicationContext的子类并重写initPropertySources())。

      1
      2
      3
      4
      5
      6
      7
      8
      /**
      * <p>Replace any stub property sources with actual instances.
      * @see org.springframework.core.env.PropertySource.StubPropertySource
      * @see org.springframework.web.context.support.WebApplicationContextUtils#initServletPropertySources
      */
      protected void initPropertySources() {
      // For subclasses: do nothing by default.
      }
      • 重写例子:

    • ⑤调用getEnvironment().validateRequiredProperties(),获取Environment对象(之前已经创建过了),并加载当前系统的同性值到Environment对象中。在getEnvironment()中会实例化StandardEnvironment,实例化时会调用父类AbstractEnvironment的构造方法,此父类构造方法会调用空方法customizePropertySources(this.propertySources),实际调用的是子类StandardEnvironment实现好的customizePropertySources(this.propertySources)方法,如下:

      1
      2
      3
      4
      5
      6
      7
      @Override
      protected void customizePropertySources(MutablePropertySources propertySources) {
      propertySources.addLast(
      new PropertiesPropertySource(SYSTEM_PROPERTIES_PROPERTY_SOURCE_NAME, getSystemProperties()));
      propertySources.addLast(
      new SystemEnvironmentPropertySource(SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME, getSystemEnvironment()));
      }

      validateRequiredProperties()用于验证requiredProperties中的环境变量是否存在,不存在则抛出异常:

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      //AbstractPropertyResolver类中
      @Override
      public void validateRequiredProperties() {
      MissingRequiredPropertiesException ex = new MissingRequiredPropertiesException();
      for (String key : this.requiredProperties) {
      if (this.getProperty(key) == null) {
      ex.addMissingRequiredProperty(key);
      }
      }
      if (!ex.getMissingRequiredProperties().isEmpty()) {
      throw ex;
      }
      }
    • ⑥调用this.earlyApplicationListeners = new LinkedHashSet<>(this.applicationListeners)准备监听器和this.earlyApplicationEvents = new LinkedHashSet<>()准备事件的集合对象,保存容器中的一些早期的事件,当以后事件派发器创建完成后将这些早期事件派发出去,默认为空的集合。

  • 打断点进入AbstractApplicationContext.obtainFreshBeanFactory()方法,作用是返回bean工厂。

    1
    2
    3
    4
    5
    6
    7
    protected ConfigurableListableBeanFactory obtainFreshBeanFactory() {
    //为beanfactory生成唯一序列化id,beanfactory已经在GenericApplicationContext构造函数中初始化了,refreshBeanFactory的逻辑在AbstractApplicationContext的实现类GenericApplicationContext中
    //初始化BeanFactory,并进行XML文件读取,并将得到的BeanFactory记录在当前实体的属性中
    refreshBeanFactory();
    //返回当前实体的beanFactory属性
    return getBeanFactory();
    }

    注解版

    • ①调用GenericApplicationContext.refreshBeanFactory(),即刷新【创建】BeanFactory。

      1
      2
      3
      4
      5
      6
      7
      8
      9
        // 注解版,GenericApplicationContext.refreshBeanFactory()
      @Override
      protected final void refreshBeanFactory() throws IllegalStateException {
      if (!this.refreshed.compareAndSet(false, true)) {
      throw new IllegalStateException(
      "GenericApplicationContext does not support multiple refresh attempts: just call 'refresh' once");
      }
      this.beanFactory.setSerializationId(getId());
      }
      • ①GenericApplicationContext类的构造器创建了一个this.beanFactory = new DefaultListableBeanFactory()。
      • ②设置序列化id:this.beanFactory.setSerializationId(this.getId())。
    • ②调用GenericApplicationContext.getBeanFactory(),即返回刚才GenericApplicationContext创建的BeanFactory对象,此时返回的BeanFactory都只是一些默认的设置。

    • ③将创建的BeanFactory【DefaultListableBeanFactory】返回。

    xml版

    • ①调用AbstractRefreshableApplicationContext.refreshBeanFactory(),即刷新【创建】BeanFactory。

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      16
      17
      18
      19
      20
      21
      22
      23
      24
      //xml版,AbstractRefreshableApplicationContext.refreshBeanFactory()
      protected final void refreshBeanFactory() throws BeansException {
      //如果存在beanFactory,则销毁beanFactory
      if (hasBeanFactory()) {
      destroyBeans();
      closeBeanFactory();
      }
      try {
      //创建Bean工厂DefaultListableBeanFactory
      DefaultListableBeanFactory beanFactory = createBeanFactory();
      //序列化指定id,可以从id反序列化到beanFactory对象
      beanFactory.setSerializationId(getId());
      //定制beanFactory,设置相关属性包括是否允许覆盖同名称的不同定义的对象以及循环依赖
      customizeBeanFactory(beanFactory);
      //初始化documentReader,并进行xml解析
      loadBeanDefinitions(beanFactory);
      synchronized (this.beanFactoryMonitor) {
      this.beanFactory = beanFactory;
      }
      }
      catch (IOException ex) {
      throw new ApplicationContextException("I/O error parsing bean definition source for " + getDisplayName(), ex);
      }
      }
      • ①调用AbstractRefreshableApplicationContext.createBeanFactory()创建一个Bean工厂DefaultListableBeanFactory。

        1
        2
        3
        protected DefaultListableBeanFactory createBeanFactory() {
        return new DefaultListableBeanFactory(getInternalParentBeanFactory());
        }
      • ②设置序列化id:this.beanFactory.setSerializationId(this.getId())。

        1
        2
        3
        4
        5
        6
        7
        8
        9
        public void setSerializationId(@Nullable String serializationId) {
        if (serializationId != null) {
        serializableFactories.put(serializationId, new WeakReference<>(this));
        }
        else if (this.serializationId != null) {
        serializableFactories.remove(this.serializationId);
        }
        this.serializationId = serializationId;
        }
      • ③定制beanFactory,设置相关属性包括是否允许覆盖同名称的不同定义的对象以及循环依赖。

        1
        2
        3
        4
        5
        6
        7
        8
        9
        10
        11
        12
        protected void customizeBeanFactory(DefaultListableBeanFactory beanFactory) {
        //如果属性allowBeanDefinition0verriding不为空,设置给beanFactory对象相应属性,是否允许覆益同名称的不同定义的对象
        //这里this.allowBeanDefinitionOverriding默认为null
        if (this.allowBeanDefinitionOverriding != null) {
        beanFactory.setAllowBeanDefinitionOverriding(this.allowBeanDefinitionOverriding);
        }
        //如果属性alLowcircularReferences不为空,设置给beanFactory对象相应属性,是否允许bean之间存在循环依赖
        //这里this.allowCircularReferences默认为null
        if (this.allowCircularReferences != null) {
        beanFactory.setAllowCircularReferences(this.allowCircularReferences);
        }
        }

        这里子类可以扩展实现customizeBeanFactory方法,涉及两个属性,一是allowBeanDefinitionOverriding:是否允许覆盖同名称的不同定义的对象;二是allowCircularReferences:是否允许bean之间存在循环依赖。

      • ④执行loadBeanDefinitions(beanFactory)初始化documentReader,并进行xml解析。

        1
        2
        3
        4
        5
        6
        7
        8
        9
        10
        11
        12
        13
        14
        15
        16
        17
        18
        19
        20
        21
        @Override
        protected void loadBeanDefinitions(DefaultListableBeanFactory beanFactory) throws BeansException, IOException {
        // Create a new XmlBeanDefinitionReader for the given BeanFactory.
        //创建一个xml的beanDefinitionReader,并通过回调设置到beanFactory中
        XmlBeanDefinitionReader beanDefinitionReader = new XmlBeanDefinitionReader(beanFactory);

        // Configure the bean definition reader with this context's
        // resource loading environment.
        //给reader对象设置环境对象
        beanDefinitionReader.setEnvironment(this.getEnvironment());
        beanDefinitionReader.setResourceLoader(this);
        //验证文件的默认加载方式是网络加载,这样可能很慢,体验不好。所以自定义EntityResolver加载本地的校验文件
        beanDefinitionReader.setEntityResolver(new ResourceEntityResolver(this));

        // Allow a subclass to provide custom initialization of the reader,
        // then proceed with actually loading the bean definitions.
        //初始化beanDefinitionReader对象,此处设置配置文件是否要进行验证
        initBeanDefinitionReader(beanDefinitionReader);
        //开始完成beanDefinition的加载
        loadBeanDefinitions(beanDefinitionReader);
        }
        • ①这里会通过调用beanDefinitionReader.setEntityResolver(new ResourceEntityResolver(this))给beanDefinitionReader设置ResourceEntityResolver用于加载本地的校验文件。

          1
          2
          3
          4
          public ResourceEntityResolver(ResourceLoader resourceLoader) {
          super(resourceLoader.getClassLoader());
          this.resourceLoader = resourceLoader;
          }
          1
          2
          3
          4
          5
          6
          7
          public DelegatingEntityResolver(@Nullable ClassLoader classLoader) {
          //如果bean标签的定义信息使用的是dtd格式后缀的则使用BeansDtdResolver解析
          this.dtdResolver = new BeansDtdResolver();
          //当完成这行代码的调用之后,大家神奇的发现一件事情,schemaResolver对象的schemaMappings属性被完成了赋值操作,但是你遍历完成所有代码后依然没有看到显式调用
          //其实此时的原理是非常简单的,我们在进行debug的时候,因为在程序运行期间需要显示当前类的所有信息,所以idea会帮助我们调用tostring方法,只不过此过程我们识别不到而已
          this.schemaResolver = new PluggableSchemaResolver(classLoader);
          }
          1
          2
          3
          4
          public PluggableSchemaResolver(@Nullable ClassLoader classLoader) {
          this.classLoader = classLoader;
          this.schemaMappingsLocation = DEFAULT_SCHEMA_MAPPINGS_LOCATION;
          }
        • ②最后调用loadBeanDefinitions(beanDefinitionReader)开始完成beanDefinition的加载。

          1
          2
          3
          4
          5
          6
          7
          8
          9
          10
          11
          12
          protected void loadBeanDefinitions(XmlBeanDefinitionReader reader) throws BeansException, IOException {
          //以Resource的方式获得配置文件的资源位置
          Resource[] configResources = getConfigResources();
          if (configResources != null) {
          reader.loadBeanDefinitions(configResources);
          }
          //以string的形式获得配置文件的位置
          String[] configLocations = getConfigLocations();
          if (configLocations != null) {
          reader.loadBeanDefinitions(configLocations);
          }
          }

          由于ClassPathXmlApplicationContext的构造方法没有传入paths,所以getConfigResources()返回null,不会执行第一个if块;而之前已经设置过ConfigLocations,所以getConfigLocations()不为null,执行第二个if块即reader.loadBeanDefinitions(configLocations)。

          1
          2
          3
          4
          5
          6
          7
          8
          9
          10
          @Override
          public int loadBeanDefinitions(String... locations) throws BeanDefinitionStoreException {
          Assert.notNull(locations, "Location array must not be null");
          int count = 0;
          //循环配置文件数组依次完成解析工作
          for (String location : locations) {
          count += loadBeanDefinitions(location);
          }
          return count;
          }

          执行到count += loadBeanDefinitions(location)解析第一个配置文件。

          1
          2
          3
          4
          @Override
          public int loadBeanDefinitions(String location) throws BeanDefinitionStoreException {
          return loadBeanDefinitions(location, null);
          }
          1
          2
          3
          4
          5
          6
          7
          8
          9
          10
          11
          12
          13
          14
          15
          16
          17
          18
          19
          20
          21
          22
          23
          24
          25
          26
          27
          28
          29
          30
          31
          32
          33
          34
          35
          36
          37
          38
          39
          40
          public int loadBeanDefinitions(String location, @Nullable Set<Resource> actualResources) throws BeanDefinitionStoreException {
          //此处获取resourceLoader对象,即ClassPathXmlApplicationContext,之前在beanDefinitionReader.setResourceLoader(this)中设置过
          ResourceLoader resourceLoader = getResourceLoader();
          if (resourceLoader == null) {
          throw new BeanDefinitionStoreException(
          "Cannot load bean definitions from location [" + location + "]: no ResourceLoader available");
          }

          if (resourceLoader instanceof ResourcePatternResolver) {
          // Resource pattern matching available.
          try {
          //调用DefaultResourceLoader的getResource完成具体的Resource定位,里面使用到resourcePatternResolver,在之前ClassPathXmlApplicationContext的构造方法中的super(parent)中被设置,实际类型是PathMatchingResourcePatternResolver
          Resource[] resources = ((ResourcePatternResolver) resourceLoader).getResources(location);
          int count = loadBeanDefinitions(resources);
          if (actualResources != null) {
          Collections.addAll(actualResources, resources);
          }
          if (logger.isTraceEnabled()) {
          logger.trace("Loaded " + count + " bean definitions from location pattern [" + location + "]");
          }
          return count;
          }
          catch (IOException ex) {
          throw new BeanDefinitionStoreException(
          "Could not resolve bean definition resource pattern [" + location + "]", ex);
          }
          }
          else {
          // Can only load single resources by absolute URL.
          Resource resource = resourceLoader.getResource(location);
          int count = loadBeanDefinitions(resource);
          if (actualResources != null) {
          actualResources.add(resource);
          }
          if (logger.isTraceEnabled()) {
          logger.trace("Loaded " + count + " bean definitions from location [" + location + "]");
          }
          return count;
          }
          }

          这里面获取到Resource数组后调用loadBeanDefinitions(resources)循环获取Resource进行解析。

          1
          2
          3
          4
          5
          6
          7
          8
          9
          @Override
          public int loadBeanDefinitions(Resource... resources) throws BeanDefinitionStoreException {
          Assert.notNull(resources, "Resource array must not be null");
          int count = 0;
          for (Resource resource : resources) {
          count += loadBeanDefinitions(resource);
          }
          return count;
          }

          执行到count += loadBeanDefinitions(resource)解析第一个Resource。

          1
          2
          3
          4
          @Override
          public int loadBeanDefinitions(Resource resource) throws BeanDefinitionStoreException {
          return loadBeanDefinitions(new EncodedResource(resource));
          }
          1
          2
          3
          4
          5
          6
          7
          8
          9
          10
          11
          12
          13
          14
          15
          16
          17
          18
          19
          20
          21
          22
          23
          24
          25
          26
          27
          28
          29
          30
          31
          32
          33
          34
          35
          public int loadBeanDefinitions(EncodedResource encodedResource) throws BeanDefinitionStoreException {
          Assert.notNull(encodedResource, "EncodedResource must not be null");
          if (logger.isTraceEnabled()) {
          logger.trace("Loading XML bean definitions from " + encodedResource);
          }
          //通过属性来记录已经加载的资源,这里返回null
          Set<EncodedResource> currentResources = this.resourcesCurrentlyBeingLoaded.get();
          if (currentResources == null) {
          currentResources = new HashSet<>(4);
          this.resourcesCurrentlyBeingLoaded.set(currentResources);
          }
          if (!currentResources.add(encodedResource)) {
          throw new BeanDefinitionStoreException(
          "Detected cyclic loading of " + encodedResource + " - check your import definitions!");
          }
          //从encodedResource中获取已经封装的Resource对象并再次从Resource中获取其中的inputStream
          try (InputStream inputStream = encodedResource.getResource().getInputStream()) {
          InputSource inputSource = new InputSource(inputStream);
          if (encodedResource.getEncoding() != null) {
          inputSource.setEncoding(encodedResource.getEncoding());
          }
          //逻辑处理的核心步骤
          return doLoadBeanDefinitions(inputSource, encodedResource.getResource());
          }
          catch (IOException ex) {
          throw new BeanDefinitionStoreException(
          "IOException parsing XML document from " + encodedResource.getResource(), ex);
          }
          finally {
          currentResources.remove(encodedResource);
          if (currentResources.isEmpty()) {
          this.resourcesCurrentlyBeingLoaded.remove();
          }
          }
          }

          这里执行doLoadBeanDefinitions(inputSource, encodedResource.getResource())进入了核心的解析步骤。

          1
          2
          3
          4
          5
          6
          7
          8
          9
          10
          11
          12
          13
          14
          15
          16
          17
          18
          19
          20
          21
          22
          23
          24
          25
          26
          27
          28
          29
          30
          31
          32
          33
          34
          35
          36
          37
          protected int doLoadBeanDefinitions(InputSource inputSource, Resource resource)
          throws BeanDefinitionStoreException {

          try {
          //此处获取xml文件的document对象,这个解析过程是由documentLoader完成的
          //从string[]-string-Resource[]-resource,最终将resource读取成一个个Document文档,根据文档的节点信息封装成一个个BeanDefinition对象
          Document doc = doLoadDocument(inputSource, resource);
          int count = registerBeanDefinitions(doc, resource);
          if (logger.isDebugEnabled()) {
          logger.debug("Loaded " + count + " bean definitions from " + resource);
          }
          return count;
          }
          catch (BeanDefinitionStoreException ex) {
          throw ex;
          }
          catch (SAXParseException ex) {
          throw new XmlBeanDefinitionStoreException(resource.getDescription(),
          "Line " + ex.getLineNumber() + " in XML document from " + resource + " is invalid", ex);
          }
          catch (SAXException ex) {
          throw new XmlBeanDefinitionStoreException(resource.getDescription(),
          "XML document from " + resource + " is invalid", ex);
          }
          catch (ParserConfigurationException ex) {
          throw new BeanDefinitionStoreException(resource.getDescription(),
          "Parser configuration exception parsing XML from " + resource, ex);
          }
          catch (IOException ex) {
          throw new BeanDefinitionStoreException(resource.getDescription(),
          "IOException parsing XML document from " + resource, ex);
          }
          catch (Throwable ex) {
          throw new BeanDefinitionStoreException(resource.getDescription(),
          "Unexpected exception parsing XML document from " + resource, ex);
          }
          }

          在获取到xml文件的document对象(包含node父子节点信息)后,会接着调用registerBeanDefinitions(doc, resource)读取document对象里的节点信息。

          1
          2
          3
          4
          5
          6
          7
          8
          public int registerBeanDefinitions(Document doc, Resource resource) throws BeanDefinitionStoreException {
          //对xml的beanDefinition进行解析
          BeanDefinitionDocumentReader documentReader = createBeanDefinitionDocumentReader();
          int countBefore = getRegistry().getBeanDefinitionCount();
          //完成具体的解析过程
          documentReader.registerBeanDefinitions(doc, createReaderContext(resource));
          return getRegistry().getBeanDefinitionCount() - countBefore;
          }

          接着调用documentReader.registerBeanDefinitions(doc, createReaderContext(resource))完成具体解析过程。

          1
          2
          3
          4
          5
          6
          @Override
          public void registerBeanDefinitions(Document doc, XmlReaderContext readerContext) {
          this.readerContext = readerContext;
          //doc.getDocumentElement()即为获取Document的顶级父级元素
          doRegisterBeanDefinitions(doc.getDocumentElement());
          }
          1
          2
          3
          4
          5
          6
          7
          8
          9
          10
          11
          12
          13
          14
          15
          16
          17
          18
          19
          20
          21
          22
          23
          24
          25
          26
          27
          28
          29
          30
          31
          32
          33
          34
          @SuppressWarnings("deprecation")  // for Environment.acceptsProfiles(String...)
          protected void doRegisterBeanDefinitions(Element root) {
          // Any nested <beans> elements will cause recursion in this method. In
          // order to propagate and preserve <beans> default-* attributes correctly,
          // keep track of the current (parent) delegate, which may be null. Create
          // the new (child) delegate with a reference to the parent for fallback purposes,
          // then ultimately reset this.delegate back to its original (parent) reference.
          // this behavior emulates a stack of delegates without actually necessitating one.
          BeanDefinitionParserDelegate parent = this.delegate;
          this.delegate = createDelegate(getReaderContext(), root, parent);

          if (this.delegate.isDefaultNamespace(root)) {
          String profileSpec = root.getAttribute(PROFILE_ATTRIBUTE);
          if (StringUtils.hasText(profileSpec)) {
          String[] specifiedProfiles = StringUtils.tokenizeToStringArray(
          profileSpec, BeanDefinitionParserDelegate.MULTI_VALUE_ATTRIBUTE_DELIMITERS);
          // We cannot use Profiles.of(...) since profile expressions are not supported
          // in XML config. See SPR-12458 for details.
          if (!getReaderContext().getEnvironment().acceptsProfiles(specifiedProfiles)) {
          if (logger.isDebugEnabled()) {
          logger.debug("Skipped XML bean definition file due to specified profiles [" + profileSpec +
          "] not matching: " + getReaderContext().getResource());
          }
          return;
          }
          }
          }

          preProcessXml(root);
          parseBeanDefinitions(root, this.delegate);
          postProcessXml(root);

          this.delegate = parent;
          }

          调用parseBeanDefinitions(root, this.delegate)利用delegate从Document的根节点开始往下解析。

          1
          2
          3
          4
          5
          6
          7
          8
          9
          10
          11
          12
          13
          14
          15
          16
          17
          18
          19
          20
          21
          22
          23
          24
          25
          /**
          * Parse the elements at the root level in the document:
          * "import", "alias", "bean".
          * @param root the DOM root element of the document
          */
          protected void parseBeanDefinitions(Element root, BeanDefinitionParserDelegate delegate) {
          if (delegate.isDefaultNamespace(root)) {
          NodeList nl = root.getChildNodes();
          for (int i = 0; i < nl.getLength(); i++) {
          Node node = nl.item(i);
          if (node instanceof Element) {
          Element ele = (Element) node;
          if (delegate.isDefaultNamespace(ele)) {
          parseDefaultElement(ele, delegate);
          }
          else {
          delegate.parseCustomElement(ele);
          }
          }
          }
          }
          else {
          delegate.parseCustomElement(root);
          }
          }

          由于解析到的<bean>标签是默认名称空间里的,所以执行parseDefaultElement(ele, delegate)。

          1
          2
          3
          4
          5
          6
          7
          8
          9
          10
          11
          12
          13
          14
          15
          16
          private void parseDefaultElement(Element ele, BeanDefinitionParserDelegate delegate) {
          if (delegate.nodeNameEquals(ele, IMPORT_ELEMENT)) {
          importBeanDefinitionResource(ele);
          }
          else if (delegate.nodeNameEquals(ele, ALIAS_ELEMENT)) {
          processAliasRegistration(ele);
          }
          else if (delegate.nodeNameEquals(ele, BEAN_ELEMENT)) {
          //执行此方法
          processBeanDefinition(ele, delegate);
          }
          else if (delegate.nodeNameEquals(ele, NESTED_BEANS_ELEMENT)) {
          // recurse
          doRegisterBeanDefinitions(ele);
          }
          }
          1
          2
          3
          4
          5
          6
          7
          8
          9
          10
          11
          12
          13
          14
          15
          16
          17
          18
          19
          20
          protected void processBeanDefinition(Element ele, BeanDefinitionParserDelegate delegate) {
          //beanDefinitionHolder是beanDefinition对象的封装类,封装了BeanDefinition,bean的名字和别名,用它来完成向IOC容器的注册
          //得到这个beanDefinitionHolder就意味着beanDefinition是通过BeanDefinitionParserDelegate对xml元素的信息按照spring的bean规则进行解析得到的
          BeanDefinitionHolder bdHolder = delegate.parseBeanDefinitionElement(ele);
          if (bdHolder != null) {
          bdHolder = delegate.decorateBeanDefinitionIfRequired(ele, bdHolder);
          try {
          // Register the final decorated instance.
          //向ioc容器注册解析得到的beanDefinition的地方
          BeanDefinitionReaderUtils.registerBeanDefinition(bdHolder, getReaderContext().getRegistry());
          }
          catch (BeanDefinitionStoreException ex) {
          getReaderContext().error("Failed to register bean definition with name '" +
          bdHolder.getBeanName() + "'", ele, ex);
          }
          // Send registration event.
          //在beanDefinition向ioc容器注册完成之后,发送消息
          getReaderContext().fireComponentRegistered(new BeanComponentDefinition(bdHolder));
          }
          }
          • ①首先调用delegate.parseBeanDefinitionElement(ele)完成解析。

            1
            2
            3
            4
            @Nullable
            public BeanDefinitionHolder parseBeanDefinitionElement(Element ele) {
            return parseBeanDefinitionElement(ele, null);
            }
            1
            2
            3
            4
            5
            6
            7
            8
            9
            10
            11
            12
            13
            14
            15
            16
            17
            18
            19
            20
            21
            22
            23
            24
            25
            26
            27
            28
            29
            30
            31
            32
            33
            34
            35
            36
            37
            38
            39
            40
            41
            42
            43
            44
            45
            46
            47
            48
            49
            50
            51
            52
            53
            54
            55
            56
            57
            58
            59
            60
            61
            62
            63
            @Nullable
            public BeanDefinitionHolder parseBeanDefinitionElement(Element ele, @Nullable BeanDefinition containingBean) {
            //解析id属性
            String id = ele.getAttribute(ID_ATTRIBUTE);
            //解析name属性
            String nameAttr = ele.getAttribute(NAME_ATTRIBUTE);
            //如果bean有别名的话,那么将别名分割解析
            List<String> aliases = new ArrayList<>();
            if (StringUtils.hasLength(nameAttr)) {
            String[] nameArr = StringUtils.tokenizeToStringArray(nameAttr, MULTI_VALUE_ATTRIBUTE_DELIMITERS);
            aliases.addAll(Arrays.asList(nameArr));
            }

            String beanName = id;
            if (!StringUtils.hasText(beanName) && !aliases.isEmpty()) {
            beanName = aliases.remove(0);
            if (logger.isTraceEnabled()) {
            logger.trace("No XML 'id' specified - using '" + beanName +
            "' as bean name and " + aliases + " as aliases");
            }
            }

            if (containingBean == null) {
            checkNameUniqueness(beanName, aliases, ele);
            }
            //对bean元素的详细解析
            AbstractBeanDefinition beanDefinition = parseBeanDefinitionElement(ele, beanName, containingBean);
            if (beanDefinition != null) {
            if (!StringUtils.hasText(beanName)) {
            try {
            //如果不存在beanName,那么根据spring中提供的命名规则为当前bean生成对应的beanName
            if (containingBean != null) {
            beanName = BeanDefinitionReaderUtils.generateBeanName(
            beanDefinition, this.readerContext.getRegistry(), true);
            }
            else {
            beanName = this.readerContext.generateBeanName(beanDefinition);
            // Register an alias for the plain bean class name, if still possible,
            // if the generator returned the class name plus a suffix.
            // This is expected for Spring 1.2/2.0 backwards compatibility.
            String beanClassName = beanDefinition.getBeanClassName();
            if (beanClassName != null &&
            beanName.startsWith(beanClassName) && beanName.length() > beanClassName.length() &&
            !this.readerContext.getRegistry().isBeanNameInUse(beanClassName)) {
            aliases.add(beanClassName);
            }
            }
            if (logger.isTraceEnabled()) {
            logger.trace("Neither XML 'id' nor 'name' specified - " +
            "using generated bean name [" + beanName + "]");
            }
            }
            catch (Exception ex) {
            error(ex.getMessage(), ele);
            return null;
            }
            }
            String[] aliasesArray = StringUtils.toStringArray(aliases);
            return new BeanDefinitionHolder(beanDefinition, beanName, aliasesArray);
            }

            return null;
            }

            里面调用parseBeanDefinitionElement(ele, beanName, containingBean)进行对bean标签进行详细解析。

            1
            2
            3
            4
            5
            6
            7
            8
            9
            10
            11
            12
            13
            14
            15
            16
            17
            18
            19
            20
            21
            22
            23
            24
            25
            26
            27
            28
            29
            30
            31
            32
            33
            34
            35
            36
            37
            38
            39
            40
            41
            42
            43
            44
            45
            46
            47
            48
            49
            50
            51
            52
            53
            54
            55
            56
            @Nullable
            public AbstractBeanDefinition parseBeanDefinitionElement(
            Element ele, String beanName, @Nullable BeanDefinition containingBean) {

            this.parseState.push(new BeanEntry(beanName));
            //解析class属性
            String className = null;
            if (ele.hasAttribute(CLASS_ATTRIBUTE)) {
            className = ele.getAttribute(CLASS_ATTRIBUTE).trim();
            }
            //解析parent属性
            String parent = null;
            if (ele.hasAttribute(PARENT_ATTRIBUTE)) {
            parent = ele.getAttribute(PARENT_ATTRIBUTE);
            }

            try {
            //创建装在bean信息的AbstractBeanDefinition对象,实际的实现是GenericBeanDefinition
            AbstractBeanDefinition bd = createBeanDefinition(className, parent);
            //解析bean标签的各种其他属性
            parseBeanDefinitionAttributes(ele, beanName, containingBean, bd);
            //设置description信息
            bd.setDescription(DomUtils.getChildElementValueByTagName(ele, DESCRIPTION_ELEMENT));
            //解析元数据
            parseMetaElements(ele, bd);
            //解析lookup-method属性
            parseLookupOverrideSubElements(ele, bd.getMethodOverrides());
            //解析replaced-method属性
            parseReplacedMethodSubElements(ele, bd.getMethodOverrides());
            //解析构造函数参数
            parseConstructorArgElements(ele, bd);
            //解析property子元素
            parsePropertyElements(ele, bd);
            //解析qualifier子元素
            parseQualifierElements(ele, bd);

            bd.setResource(this.readerContext.getResource());
            bd.setSource(extractSource(ele));

            return bd;
            }
            catch (ClassNotFoundException ex) {
            error("Bean class [" + className + "] not found", ele, ex);
            }
            catch (NoClassDefFoundError err) {
            error("Class that bean class [" + className + "] depends on not found", ele, err);
            }
            catch (Throwable ex) {
            error("Unexpected failure during bean definition parsing", ele, ex);
            }
            finally {
            this.parseState.pop();
            }

            return null;
            }
          • ②接着调用BeanDefinitionReaderUtils.registerBeanDefinition(bdHolder, getReaderContext().getRegistry())向ioc容器注册解析得到的beanDefinition的地方。

            1
            2
            3
            4
            5
            6
            7
            8
            9
            10
            11
            12
            13
            14
            15
            16
            17
            18
            19
            public static void registerBeanDefinition(
            BeanDefinitionHolder definitionHolder, BeanDefinitionRegistry registry)
            throws BeanDefinitionStoreException {

            // Register bean definition under primary name.
            //使用beanName做唯一标识注册
            String beanName = definitionHolder.getBeanName();
            //将bean的信息添加到Map<String, BeanDefinition> beanDefinitionMap中
            registry.registerBeanDefinition(beanName, definitionHolder.getBeanDefinition());

            // Register aliases for bean name, if any.
            //注册所有的别名
            String[] aliases = definitionHolder.getAliases();
            if (aliases != null) {
            for (String alias : aliases) {
            registry.registerAlias(beanName, alias);
            }
            }
            }
            • ①调用registry.registerBeanDefinition(beanName, definitionHolder.getBeanDefinition())将bean的信息添加到beanDefinitionMap中一以及记录beanName。

              1
              2
              3
              4
              5
              6
              7
              8
              9
              10
              11
              12
              13
              14
              15
              16
              17
              18
              19
              20
              21
              22
              23
              24
              25
              26
              27
              28
              29
              30
              31
              32
              33
              34
              35
              36
              37
              38
              39
              40
              41
              42
              43
              44
              45
              46
              47
              48
              49
              50
              51
              52
              53
              54
              55
              56
              57
              58
              59
              60
              61
              62
              63
              64
              65
              66
              67
              68
              69
              70
              71
              72
              73
              74
              75
              76
              77
              @Override
              public void registerBeanDefinition(String beanName, BeanDefinition beanDefinition)
              throws BeanDefinitionStoreException {

              Assert.hasText(beanName, "Bean name must not be empty");
              Assert.notNull(beanDefinition, "BeanDefinition must not be null");

              if (beanDefinition instanceof AbstractBeanDefinition) {
              try {
              //注册前的最后一个校验,这里的检验不同于之前的xm1文件校验,主要是对应abstractBeanDefinition属性的method0verrides校验,检验methodOverrides是否与工厂方法并存或者methodoverrides对应的方法根本不存在
              ((AbstractBeanDefinition) beanDefinition).validate();
              }
              catch (BeanDefinitionValidationException ex) {
              throw new BeanDefinitionStoreException(beanDefinition.getResourceDescription(), beanName,
              "Validation of bean definition failed", ex);
              }
              }

              BeanDefinition existingDefinition = this.beanDefinitionMap.get(beanName);
              //处理注册已经注册的beanName情况
              if (existingDefinition != null) {
              //如果对应的beanName已经注册且在配置中配置了bean不允许被覆盖,则抛出异常
              if (!isAllowBeanDefinitionOverriding()) {
              throw new BeanDefinitionOverrideException(beanName, beanDefinition, existingDefinition);
              }
              else if (existingDefinition.getRole() < beanDefinition.getRole()) {
              // e.g. was ROLE_APPLICATION, now overriding with ROLE_SUPPORT or ROLE_INFRASTRUCTURE
              if (logger.isInfoEnabled()) {
              logger.info("Overriding user-defined bean definition for bean '" + beanName +
              "' with a framework-generated bean definition: replacing [" +
              existingDefinition + "] with [" + beanDefinition + "]");
              }
              }
              else if (!beanDefinition.equals(existingDefinition)) {
              if (logger.isDebugEnabled()) {
              logger.debug("Overriding bean definition for bean '" + beanName +
              "' with a different definition: replacing [" + existingDefinition +
              "] with [" + beanDefinition + "]");
              }
              }
              else {
              if (logger.isTraceEnabled()) {
              logger.trace("Overriding bean definition for bean '" + beanName +
              "' with an equivalent definition: replacing [" + existingDefinition +
              "] with [" + beanDefinition + "]");
              }
              }
              this.beanDefinitionMap.put(beanName, beanDefinition);
              }
              else {
              if (hasBeanCreationStarted()) {
              // Cannot modify startup-time collection elements anymore (for stable iteration)
              synchronized (this.beanDefinitionMap) {
              this.beanDefinitionMap.put(beanName, beanDefinition);
              List<String> updatedDefinitions = new ArrayList<>(this.beanDefinitionNames.size() + 1);
              updatedDefinitions.addAll(this.beanDefinitionNames);
              updatedDefinitions.add(beanName);
              this.beanDefinitionNames = updatedDefinitions;
              removeManualSingletonName(beanName);
              }
              }
              else {
              // Still in startup registration phase
              //注册beanDefinition
              this.beanDefinitionMap.put(beanName, beanDefinition);
              //记录beanName
              this.beanDefinitionNames.add(beanName);
              removeManualSingletonName(beanName);
              }
              this.frozenBeanDefinitionNames = null;
              }

              if (existingDefinition != null || containsSingleton(beanName)) {
              //重置所有beanName对应的缓存
              resetBeanDefinition(beanName);
              }
              }
            • ②调用registry.registerAlias(beanName, alias)注册所有的别名,将别名放到Map<String, String> aliasMap中。

              1
              2
              3
              4
              @Override
              public void registerAlias(String beanName, String alias) {
              this.beanFactory.registerAlias(beanName, alias);
              }
              1
              2
              3
              4
              5
              6
              7
              8
              9
              10
              11
              12
              13
              14
              15
              16
              17
              18
              19
              20
              21
              22
              23
              24
              25
              26
              27
              28
              29
              30
              31
              32
              33
              34
              35
              36
              37
              38
              @Override
              public void registerAlias(String name, String alias) {
              Assert.hasText(name, "'name' must not be empty");
              Assert.hasText(alias, "'alias' must not be empty");
              synchronized (this.aliasMap) {
              //如果beanName与alias相同的话不记录alias,并删除alias
              if (alias.equals(name)) {
              this.aliasMap.remove(alias);
              if (logger.isDebugEnabled()) {
              logger.debug("Alias definition '" + alias + "' ignored since it points to same name");
              }
              }
              else {
              String registeredName = this.aliasMap.get(alias);
              if (registeredName != null) {
              if (registeredName.equals(name)) {
              // An existing alias - no need to re-register
              return;
              }
              //如果alias不允许被覆盖则抛出异常
              if (!allowAliasOverriding()) {
              throw new IllegalStateException("Cannot define alias '" + alias + "' for name '" +
              name + "': It is already registered for name '" + registeredName + "'.");
              }
              if (logger.isDebugEnabled()) {
              logger.debug("Overriding alias '" + alias + "' definition for registered name '" +
              registeredName + "' with new target name '" + name + "'");
              }
              }
              //当A->B存在时,若再次出现A->C->B的时候回抛出异常
              checkForAliasCircle(name, alias);
              this.aliasMap.put(alias, name);
              if (logger.isTraceEnabled()) {
              logger.trace("Alias definition '" + alias + "' registered for name '" + name + "'");
              }
              }
              }
              }
          • ③调用getReaderContext().fireComponentRegistered(new BeanComponentDefinition(bdHolder))在beanDefinition向ioc容器注册完成之后,发送消息。

    • ②返回当前实体的beanFactory属性。

  • 打断点进入AbstractApplicationContext.prepareBeanFactory(beanFactory)方法,即BeanFactory的预准备工作。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    protected void prepareBeanFactory(ConfigurableListableBeanFactory beanFactory) {
    // Tell the internal bean factory to use the context's class loader etc.
    //设置类加载器。
    beanFactory.setBeanClassLoader(getClassLoader());
    //设置EL表达式解析器(Bean初始化完成后填充属性时会用到)
    beanFactory.setBeanExpressionResolver(new StandardBeanExpressionResolver(beanFactory.getBeanClassLoader()));
    //将当前的ApplicationContext对象交给ApplicationContextAwareProcessor类来处理,从而在Aware接口实现类中的注入applicationContext
    beanFactory.addPropertyEditorRegistrar(new ResourceEditorRegistrar(this, getEnvironment()));

    // Configure the bean factory with context callbacks.
    //添加一个BeanPostProcessor的实现ApplicationContextAwareProcessor。
    beanFactory.addBeanPostProcessor(new ApplicationContextAwareProcessor(this));
    //设置忽略的自动装配接口,表示这些接口的实现类不允许通过接口自动注入。
    beanFactory.ignoreDependencyInterface(EnvironmentAware.class);
    beanFactory.ignoreDependencyInterface(EmbeddedValueResolverAware.class);
    beanFactory.ignoreDependencyInterface(ResourceLoaderAware.class);
    beanFactory.ignoreDependencyInterface(ApplicationEventPublisherAware.class);
    beanFactory.ignoreDependencyInterface(MessageSourceAware.class);
    beanFactory.ignoreDependencyInterface(ApplicationContextAware.class);

    // BeanFactory interface not registered as resolvable type in a plain factory.
    // MessageSource registered (and found for autowiring) as a bean.
    //注册可以自动装配的组件,就是可以在任何组件中允许自动注入的组件。
    beanFactory.registerResolvableDependency(BeanFactory.class, beanFactory);
    beanFactory.registerResolvableDependency(ResourceLoader.class, this);
    beanFactory.registerResolvableDependency(ApplicationEventPublisher.class, this);
    beanFactory.registerResolvableDependency(ApplicationContext.class, this);

    // Register early post-processor for detecting inner beans as ApplicationListeners.
    //添加一个BeanPostProcessor的实现ApplicationListenerDetector。
    beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(this));

    // Detect a LoadTimeWeaver and prepare for weaving, if found.
    //添加编译时的AspectJ。
    //如果当前BeanFactory包含loadTimeWeaver Bean,说明存在类加载期织入AspectJ,则把当前BeanFactory交给类加载期BeanPostProcessor实现类LoadTimeWeaverAwareProcessor来处理,从而实现类加载期织入AspectJ的目的。
    if (beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) {
    beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory));
    // Set a temporary ClassLoader for type matching.
    beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader()));
    }
    //给beanfactory容器中注册组件ConfigurableEnvironment、systemProperties、systemEnvironment。
    // Register default environment beans.
    if (!beanFactory.containsLocalBean(ENVIRONMENT_BEAN_NAME)) {
    beanFactory.registerSingleton(ENVIRONMENT_BEAN_NAME, getEnvironment());
    }
    //注册系统配置systemProperties组件Bean。
    if (!beanFactory.containsLocalBean(SYSTEM_PROPERTIES_BEAN_NAME)) {
    beanFactory.registerSingleton(SYSTEM_PROPERTIES_BEAN_NAME, getEnvironment().getSystemProperties());
    }
    //注册系统环境systemEnvironment组件Bean。
    if (!beanFactory.containsLocalBean(SYSTEM_ENVIRONMENT_BEAN_NAME)) {
    beanFactory.registerSingleton(SYSTEM_ENVIRONMENT_BEAN_NAME, getEnvironment().getSystemEnvironment());
    }
    }
    • ①设置BeanFactory的类加载器、支持表达式解析器等。
    • ②添加部分BeanPostProcessor【ApplicationContextAwareProcessor】。
    • ③设置忽略的自动装配的接口EnvironmentAware、EmbeddedValueResolverAware等。
    • ④注册可以解析的自动装配,我们能直接在任何组件中自动注入:BeanFactory、ResourceLoader、ApplicationEventPublisher(事件派发器)、ApplicationContext。
    • ⑤添加BeanPostProcessor【ApplicationListenerDetector】(后置处理器的作用是在bean初始化前后做一些操作)。
    • ⑥添加编译时的AspectJ。
    • ⑦给BeanFactory中注册一些能用的组件:environment【ConfigurableEnvironment】、systemProperties【Map<String, Object>】和systemEnvironment【Map<String, Object>】。
  • 打断点进入AbstractApplicationContext.postProcessBeanFactory(beanFactory)方法,即进行准备工作完成后的后置处理工作,此方法是空的,子类通过重写这个方法来在BeanFactory创建并预准备完成以后做进一步的设置。

    1
    2
    protected void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) {
    }
  • 打断点进入AbstractApplicationContext.invokeBeanFactoryPostProcessors(beanFactory)方法,即实例化并且执行所有已经注册了的BeanFactoryPostProcessor(BeanFactory的后置处理器)的方法。其内部执行实现了BeanFactoryPostProcessor、BeanDefinitionRegistryPostProcessor这两个接口的Processor。两个接口的关系如下图:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    protected void invokeBeanFactoryPostProcessors(ConfigurableListableBeanFactory beanFactory) {
    //执行BeanFactoryPostProcessors
    PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(beanFactory, getBeanFactoryPostProcessors());

    // Detect a LoadTimeWeaver and prepare for weaving, if found in the meantime
    // (e.g. through an @Bean method registered by ConfigurationClassPostProcessor)
    //初始化BeanFactory
    if (beanFactory.getTempClassLoader() == null && beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) {
    beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory));
    beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader()));
    }
    }
    • 主要执行PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors方法。

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      16
      17
      18
      19
      20
      21
      22
      23
      24
      25
      26
      27
      28
      29
      30
      31
      32
      33
      34
      35
      36
      37
      38
      39
      40
      41
      42
      43
      44
      45
      46
      47
      48
      49
      50
      51
      52
      53
      54
      55
      56
      57
      58
      59
      60
      61
      62
      63
      64
      65
      66
      67
      68
      69
      70
      71
      72
      73
      74
      75
      76
      77
      78
      79
      80
      81
      82
      83
      84
      85
      86
      87
      88
      89
      90
      91
      92
      93
      94
      95
      96
      97
      98
      99
      100
      101
      102
      103
      104
      105
      106
      107
      108
      109
      110
      111
      112
      113
      114
      115
      116
      117
      118
      119
      120
      121
      122
      123
      124
      125
      126
      127
      128
      129
      130
      131
      132
      133
      134
      135
      136
      137
      138
      139
      140
      141
      142
      143
      144
      145
      146
      147
      148
      149
      150
      151
      152
      153
      154
      155
      156
      157
      158
      159
      160
      161
      162
      163
      164
      165
      166
      167
      168
      169
      170
      171
      172
      173
      174
      175
      public static void invokeBeanFactoryPostProcessors(
      ConfigurableListableBeanFactory beanFactory, List<BeanFactoryPostProcessor> beanFactoryPostProcessors) {

      // Invoke BeanDefinitionRegistryPostProcessors first, if any.
      //注意这里只是存在beanName
      Set<String> processedBeans = new HashSet<>();
      // 1.判断beanFactory是否实现了BeanDefinitionRegistry接口。这里为true
      if (beanFactory instanceof BeanDefinitionRegistry) {
      BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory;
      //用于存放普通的BeanFactoryPostProcessor
      List<BeanFactoryPostProcessor> regularPostProcessors = new ArrayList<>();
      //用于存放BeanDefinitionRegistryPostProcessor
      List<BeanDefinitionRegistryPostProcessor> registryProcessors = new ArrayList<>();

      for (BeanFactoryPostProcessor postProcessor : beanFactoryPostProcessors) {
      if (postProcessor instanceof BeanDefinitionRegistryPostProcessor) {
      // 2.1 如果是BeanDefinitionRegistryPostProcessor
      BeanDefinitionRegistryPostProcessor registryProcessor =
      (BeanDefinitionRegistryPostProcessor) postProcessor;
      // 2.1.1 直接执行BeanDefinitionRegistryPostProcessor接口的postProcessBeanDefinitionRegistry方法
      registryProcessor.postProcessBeanDefinitionRegistry(registry);
      // 2.1.2 添加到registryProcessors(用于最后执行postProcessBeanFactory方法)
      registryProcessors.add(registryProcessor);
      }
      else {
      // 2.2 否则,只是普通的BeanFactoryPostProcessor
      // 2.2.1 添加到regularPostProcessors(用于最后执行postProcessBeanFactory方法)
      regularPostProcessors.add(postProcessor);
      }
      }

      // Do not initialize FactoryBeans here: We need to leave all regular beans
      // uninitialized to let the bean factory post-processors apply to them!
      // Separate between BeanDefinitionRegistryPostProcessors that implement
      // PriorityOrdered, Ordered, and the rest.
      List<BeanDefinitionRegistryPostProcessor> currentRegistryProcessors = new ArrayList<>();

      // First, invoke the BeanDefinitionRegistryPostProcessors that implement PriorityOrdered.
      // 3.1 找出所有实现BeanDefinitionRegistryPostProcessor接口的Bean的beanName
      String[] postProcessorNames =
      beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
      // 3.2 遍历postProcessorNames
      for (String ppName : postProcessorNames) {
      // 3.3 校验是否实现了PriorityOrdered接口
      if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
      // 3.4 获取ppName对应的bean实例, 添加到currentRegistryProcessors中
      // beanFactory.getBean: 这边getBean方法会触发创建ppName对应的bean对象, 目前暂不深入解析
      currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
      //标记已执行
      processedBeans.add(ppName);
      }
      }
      //将实现了PriorityOrdered优先级接口的BeanDefinitionRegistryPostProcessor进行排序
      sortPostProcessors(currentRegistryProcessors, beanFactory);
      //添加到registryProcessors(用于最后执行postProcessBeanFactory方法)
      registryProcessors.addAll(currentRegistryProcessors);
      //执行实现了PriorityOrdered优先级接口的BeanDefinitionRegistryPostProcessor的postProcessBeanDefinitionRegistry(registry)方法
      invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
      currentRegistryProcessors.clear();

      // Next, invoke the BeanDefinitionRegistryPostProcessors that implement Ordered.
      // 找出所有实现BeanDefinitionRegistryPostProcessor接口的Bean的beanName
      postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
      //遍历postProcessorNames
      for (String ppName : postProcessorNames) {
      //校验是否实现了Ordered接口
      if (!processedBeans.contains(ppName) && beanFactory.isTypeMatch(ppName, Ordered.class)) {
      //获取ppName对应的bean实例, 添加到currentRegistryProcessors中
      currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
      //标记已执行
      processedBeans.add(ppName);
      }
      }
      //将实现了Ordered优先级接口的BeanDefinitionRegistryPostProcessor进行排序
      sortPostProcessors(currentRegistryProcessors, beanFactory);
      registryProcessors.addAll(currentRegistryProcessors);
      //执行实现了Ordered顺序接口的BeanDefinitionRegistryPostProcessor的postProcessBeanDefinitionRegistry(registry)方法。
      invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
      currentRegistryProcessors.clear();

      // Finally, invoke all other BeanDefinitionRegistryPostProcessors until no further ones appear.
      boolean reiterate = true;
      while (reiterate) {
      reiterate = false;
      // 5.1 找出所有实现BeanDefinitionRegistryPostProcessor接口的类
      postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
      for (String ppName : postProcessorNames) {
      // 5.2 跳过已经执行过的
      if (!processedBeans.contains(ppName)) {
      currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
      //标记已执行
      processedBeans.add(ppName);
      //如果有BeanDefinitionRegistryPostProcessor被执行, 则有可能会产生新的BeanDefinitionRegistryPostProcessor,因此这边将reiterate赋值为true, 代表需要再循环查找一次
      reiterate = true;
      }
      }
      sortPostProcessors(currentRegistryProcessors, beanFactory);
      registryProcessors.addAll(currentRegistryProcessors);
      // 5.4 遍历currentRegistryProcessors, 执行postProcessBeanDefinitionRegistry方法
      invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
      currentRegistryProcessors.clear();
      }

      // Now, invoke the postProcessBeanFactory callback of all processors handled so far.
      //调用所有BeanDefinitionRegistryPostProcessor的postProcessBeanFactory方法(BeanDefinitionRegistryPostProcessor继承自BeanFactoryPostProcessor)
      invokeBeanFactoryPostProcessors(registryProcessors, beanFactory);
      //最后, 调用入参beanFactoryPostProcessors中的普通BeanFactoryPostProcessor的postProcessBeanFactory方法
      invokeBeanFactoryPostProcessors(regularPostProcessors, beanFactory);
      }

      else {
      // Invoke factory processors registered with the context instance.
      invokeBeanFactoryPostProcessors(beanFactoryPostProcessors, beanFactory);
      }

      // Do not initialize FactoryBeans here: We need to leave all regular beans
      // uninitialized to let the bean factory post-processors apply to them!
      //得到所有BeanFactoryPostProcessor的实现类BeanName
      String[] postProcessorNames =
      beanFactory.getBeanNamesForType(BeanFactoryPostProcessor.class, true, false);

      // Separate between BeanFactoryPostProcessors that implement PriorityOrdered,
      // Ordered, and the rest.
      //用于存放实现了PriorityOrdered接口的BeanFactoryPostProcessor
      List<BeanFactoryPostProcessor> priorityOrderedPostProcessors = new ArrayList<>();
      //用于存放实现了Ordered接口的BeanFactoryPostProcessor的beanName
      List<String> orderedPostProcessorNames = new ArrayList<>();
      //用于存放普通BeanFactoryPostProcessor的beanName
      List<String> nonOrderedPostProcessorNames = new ArrayList<>();
      //遍历postProcessorNames, 将BeanFactoryPostProcessor按实现PriorityOrdered、实现Ordered接口、普通三种区分开
      for (String ppName : postProcessorNames) {
      //跳过已经执行过的
      if (processedBeans.contains(ppName)) {
      // skip - already processed in first phase above
      }
      else if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
      priorityOrderedPostProcessors.add(beanFactory.getBean(ppName, BeanFactoryPostProcessor.class));
      }
      else if (beanFactory.isTypeMatch(ppName, Ordered.class)) {
      //添加实现了Ordered接口的BeanFactoryPostProcessor的beanName
      orderedPostProcessorNames.add(ppName);
      }
      else {
      //添加剩下的普通BeanFactoryPostProcessor的beanName
      nonOrderedPostProcessorNames.add(ppName);
      }
      }

      // First, invoke the BeanFactoryPostProcessors that implement PriorityOrdered.
      sortPostProcessors(priorityOrderedPostProcessors, beanFactory);
      //执行实现了PriorityOrdered优先级接口的BeanFactoryPostProcessor。
      invokeBeanFactoryPostProcessors(priorityOrderedPostProcessors, beanFactory);

      // Next, invoke the BeanFactoryPostProcessors that implement Ordered.
      List<BeanFactoryPostProcessor> orderedPostProcessors = new ArrayList<>(orderedPostProcessorNames.size());
      for (String postProcessorName : orderedPostProcessorNames) {
      orderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));
      }
      sortPostProcessors(orderedPostProcessors, beanFactory);
      //执行实现了Ordered顺序接口的BeanFactoryPostProcessor。
      invokeBeanFactoryPostProcessors(orderedPostProcessors, beanFactory);

      // Finally, invoke all other BeanFactoryPostProcessors.
      List<BeanFactoryPostProcessor> nonOrderedPostProcessors = new ArrayList<>(nonOrderedPostProcessorNames.size());
      for (String postProcessorName : nonOrderedPostProcessorNames) {
      nonOrderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));
      }
      //执行没有实现任何优先级或者是顺序接口的BeanFactoryPostProcessor。
      invokeBeanFactoryPostProcessors(nonOrderedPostProcessors, beanFactory);

      // Clear cached merged bean definitions since the post-processors might have
      // modified the original metadata, e.g. replacing placeholders in values...
      //清除元数据缓存(mergedBeanDefinitions、allBeanNamesByType、singletonBeanNamesByType)
      beanFactory.clearMetadataCache();
      }
      • ①初始化存放BeanFactoryPostProcessor集合。

      • ②遍历传入的beanFactoryPostProcessors集合。

        • 如果是BeanDefinitionRegistryPostProcessor则执行该接口的postProcessBeanDefinitionRegistry方法并添加到registryProcessors集合中。
        • 不属于BeanDefinitionRegistryPostProcessor的后置处理器则添加到regularPostProcessors集合中,并没有调用postProcessBeanDefinitionRegistry方法。
      • ③获取实现了PriorityOrdered接口的BeanDefinitionRegistryPostProcessor,排序后并执行BeanDefinitionRegistryPostProcessor.postProcessBeanDefinitionRegistry(registry)方法。(这里的后置处理器ConfigurationClassPostProcessor解析出了配置类里自定义的bean)

        • 获取实现了BeanDefinitionRegistryPostProcessor接口的BeanName存放进String[] postProcessorNames数组。
        • 从postProcessorNames中筛选出实现了PriorityOrdered接口的bean并分别装填到容器中。
        • 把实现了PriorityOrdered优先级接口的BeanDefinitionRegistryPostProcessor进行排序处理。
        • 添加到registryProcessors(用于最后执行postProcessBeanFactory方法)中。
        • 再执行实现了PriorityOrdered优先级接口的BeanDefinitionRegistryPostProcessor的postProcessBeanDefinitionRegistry(registry)方法。
      • ④获取实现了Ordered接口的BeanDefinitionRegistryPostProcessor,排序后并执行BeanDefinitionRegistryPostProcessor.postProcessBeanDefinitionRegistry(registry)方法。

        • 获取实现了BeanDefinitionRegistryPostProcessor接口的BeanName存放进String[] postProcessorNames数组。
        • 从postProcessorNames中筛选出实现了Ordered接口的bean并分别装填到容器中。
        • 把实现了Ordered优先级接口的BeanDefinitionRegistryPostProcessor进行排序处理。
        • 添加到registryProcessors(用于最后执行postProcessBeanFactory方法)中。
        • 再执行实现了Ordered优先级接口的BeanDefinitionRegistryPostProcessor的postProcessBeanDefinitionRegistry(registry)方法。
      • ⑤最后执行没有实现任何优先级或者是顺序接口的BeanDefinitionRegistryPostProcessors的postProcessBeanDefinitionRegistry(registry)方法,与上面类似因此不再赘述。

        • 在③④⑤步骤中processedBeans一直在默默无闻地收集包含@Order和@PriorityOrdered且实现了BeanDefinitionRegistryPostProcessor的BeanName。到了这里其实processedBeans有所有实现BeanDefinitionRegistryPostProcessor的beanClass了。而currentRegistryProcessors却一直在清空。
      • ⑥遍历执行registryProcessors(存放BeanDefinitionRegistryPostProcessor集合)中的postProcessBeanFactory(beanFactory)方法。

      • ⑦遍历执行regularPostProcessors(存放普通的BeanFactoryPostProcessor集合)中的postProcessBeanFactory(beanFactory)方法。

      • ⑧获取到所有BeanFactoryPostProcessor的实现类并根据排序接口顺序执行,和上面类似(③④⑤)。

        • 排序并执行实现了PriorityOrdered优先级接口的BeanFactoryPostProcessor的postProcessBeanFactory(beanFactory)方法。
        • 排序并执行实现了Ordered顺序接口的BeanFactoryPostProcessor的postProcessBeanFactory(beanFactory)方法。
        • 最后执行没有实现任何优先级或者是顺序接口的BeanFactoryPostProcessor的postProcessBeanFactory(beanFactory)方法。
      • ⑨清除元数据缓存(mergedBeanDefinitions、allBeanNamesByType、singletonBeanNamesByType), 因为后置处理器可能已经修改了原始元数据,例如,替换值中的占位符等。

      如果是注解版,invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry)中执行ConfigurationClassPostProcessor.postProcessBeanDefinitionRegistry(registry)的方法完成bean的扫描操作,其中重点执行了processConfigBeanDefinitions(registry)方法。

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      @Override
      public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) {
      int registryId = System.identityHashCode(registry);
      if (this.registriesPostProcessed.contains(registryId)) {
      throw new IllegalStateException(
      "postProcessBeanDefinitionRegistry already called on this post-processor against " + registry);
      }
      if (this.factoriesPostProcessed.contains(registryId)) {
      throw new IllegalStateException(
      "postProcessBeanFactory already called on this post-processor against " + registry);
      }
      this.registriesPostProcessed.add(registryId);

      processConfigBeanDefinitions(registry);
      }
      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      16
      17
      18
      19
      20
      21
      22
      23
      24
      25
      26
      27
      28
      29
      30
      31
      32
      33
      34
      35
      36
      37
      38
      39
      40
      41
      42
      43
      44
      45
      46
      47
      48
      49
      50
      51
      52
      53
      54
      55
      56
      57
      58
      59
      60
      61
      62
      63
      64
      65
      66
      67
      68
      69
      70
      71
      72
      73
      74
      75
      76
      77
      78
      79
      80
      81
      82
      83
      84
      85
      86
      87
      88
      89
      90
      91
      92
      93
      94
      95
      96
      97
      98
      99
      100
      101
      102
      103
      104
      105
      106
      107
      108
      109
      110
      111
      112
      113
      114
      115
      116
      117
      118
      119
      120
      121
      122
      123
      124
      125
      126
      127
      128
      129
      130
      131
      132
      133
      134
      135
      136
      137
      138
      139
      140
      public void processConfigBeanDefinitions(BeanDefinitionRegistry registry) {
      /**
      * 这个list用来保存
      * 添加@Configuration的类
      * 添加了@Component
      * 或者@ComponentScan
      * 或者@Import
      * 或者@ImportResource
      * 注解的类
      *
      * 唯一的区别是:如果类上加了@Configuration,对应的ConfigurationClass是full;否则是lite
      *
      * 正常情况下,第一次进入到这里的时候,只有配置类一个bean,因为如果是第一次进入到这里的话,beanDefinitionMap中,只有配置类这一个是我们程序员提供的业务类,其他的都是spring自带的后置处理器
      */
      List<BeanDefinitionHolder> configCsandidates = new ArrayList<>();
      //获取在new AnnotatedBeanDefinitionReader(this);中注入的spring自己的beanPostProcessor
      String[] candidateNames = registry.getBeanDefinitionNames();

      for (String beanName : candidateNames) {
      //根据beanName,从beanDefinitionMap中获取beanDefinition
      BeanDefinition beanDef = registry.getBeanDefinition(beanName);
      /**
      * 如果bean是配置类,configurationClass就是full,否则就是lite
      * 这里,如果当前bean 的configurationClass属性已经被设置值了,说明当前bean已经被解析过来,就无需再次解析
      */
      if (beanDef.getAttribute(ConfigurationClassUtils.CONFIGURATION_CLASS_ATTRIBUTE) != null) {
      if (logger.isDebugEnabled()) {
      logger.debug("Bean definition has already been processed as a configuration class: " + beanDef);
      }
      }
      //校验bean是否包含@Configuration,也就是校验bean是哪种配置类?注解?还是普通的配置类
      else if (ConfigurationClassUtils.checkConfigurationClassCandidate(beanDef, this.metadataReaderFactory)) {
      //将包含@Configuration的配置类包装成BeanDefinitionHolder加入configCandidates集合中
      configCandidates.add(new BeanDefinitionHolder(beanDef, beanName));
      }
      }

      // Return immediately if no @Configuration classes were found
      if (configCandidates.isEmpty()) {
      return;
      }
      /**
      * 对config类进行排序,configCandidates中保存的是项目中的配置类 (AppConfig ....),或者说是加了@Configuration注解的类
      */
      // Sort by previously determined @Order value, if applicable
      configCandidates.sort((bd1, bd2) -> {
      int i1 = ConfigurationClassUtils.getOrder(bd1.getBeanDefinition());
      int i2 = ConfigurationClassUtils.getOrder(bd2.getBeanDefinition());
      return Integer.compare(i1, i2);
      });

      // Detect any custom bean name generation strategy supplied through the enclosing application context
      SingletonBeanRegistry sbr = null;
      if (registry instanceof SingletonBeanRegistry) {
      sbr = (SingletonBeanRegistry) registry;
      if (!this.localBeanNameGeneratorSet) {
      BeanNameGenerator generator = (BeanNameGenerator) sbr.getSingleton(
      AnnotationConfigUtils.CONFIGURATION_BEAN_NAME_GENERATOR);
      if (generator != null) {
      this.componentScanBeanNameGenerator = generator;
      this.importBeanNameGenerator = generator;
      }
      }
      }

      if (this.environment == null) {
      this.environment = new StandardEnvironment();
      }

      // Parse each @Configuration class
      //实例化ConfigurationClassParser是为了解析各个配置类
      ConfigurationClassParser parser = new ConfigurationClassParser(
      this.metadataReaderFactory, this.problemReporter, this.environment,
      this.resourceLoader, this.componentScanBeanNameGenerator, registry);
      /**
      * 这两个set主要是为了去重
      * 正常情况下,下面的do...while循环中,只会循环处理所有的配置类,因为到目前,还没有普通的bean添加到beanDefinitionMap中
      */
      Set<BeanDefinitionHolder> candidates = new LinkedHashSet<>(configCandidates);
      Set<ConfigurationClass> alreadyParsed = new HashSet<>(configCandidates.size());
      do {
      /**
      * 如果将bean存入到beanDefinitionMap第三步
      *
      * 这里的candidates的个数是由项目中 配置文件的数量来决定的(或者说加了@Configuration或者@ComponentScan或者@Component注解的类)
      */
      parser.parse(candidates);
      parser.validate();

      Set<ConfigurationClass> configClasses = new LinkedHashSet<>(parser.getConfigurationClasses());
      configClasses.removeAll(alreadyParsed);

      // Read the model and create bean definitions based on its content
      if (this.reader == null) {
      this.reader = new ConfigurationClassBeanDefinitionReader(
      registry, this.sourceExtractor, this.resourceLoader, this.environment,
      this.importBeanNameGenerator, parser.getImportRegistry());
      }
      /**
      * 这里的configClasses 就是parse方法中,对import注解进行处理时,存入的;
      * 这里面存放的是import注入类返回数组对象中的bean(就是实现importSelector接口的类中返回的值,也就是要在import中注入的bean对应的全类名)
      *
      * 在这个方法里面 完成了对ImportSelector和ImportBeanDefinitionRegistrar注入的bean进行初始化
      */
      this.reader.loadBeanDefinitions(configClasses);
      alreadyParsed.addAll(configClasses);

      candidates.clear();
      if (registry.getBeanDefinitionCount() > candidateNames.length) {
      String[] newCandidateNames = registry.getBeanDefinitionNames();
      Set<String> oldCandidateNames = new HashSet<>(Arrays.asList(candidateNames));
      Set<String> alreadyParsedClasses = new HashSet<>();
      for (ConfigurationClass configurationClass : alreadyParsed) {
      alreadyParsedClasses.add(configurationClass.getMetadata().getClassName());
      }
      for (String candidateName : newCandidateNames) {
      if (!oldCandidateNames.contains(candidateName)) {
      BeanDefinition bd = registry.getBeanDefinition(candidateName);
      if (ConfigurationClassUtils.checkConfigurationClassCandidate(bd, this.metadataReaderFactory) &&
      !alreadyParsedClasses.contains(bd.getBeanClassName())) {
      candidates.add(new BeanDefinitionHolder(bd, candidateName));
      }
      }
      }
      candidateNames = newCandidateNames;
      }
      }
      while (!candidates.isEmpty());

      // Register the ImportRegistry as a bean in order to support ImportAware @Configuration classes
      if (sbr != null && !sbr.containsSingleton(IMPORT_REGISTRY_BEAN_NAME)) {
      sbr.registerSingleton(IMPORT_REGISTRY_BEAN_NAME, parser.getImportRegistry());
      }

      if (this.metadataReaderFactory instanceof CachingMetadataReaderFactory) {
      // Clear cache in externally provided MetadataReaderFactory; this is a no-op
      // for a shared cache since it'll be cleared by the ApplicationContext.
      ((CachingMetadataReaderFactory) this.metadataReaderFactory).clearCache();
      }
      }
      • 该方法中,完成了以下操作:

        • 从beanDefinitionMap中获取到添加了以下注解的类@Configuration、@ComponentScan、@Component、@Import、@ImportResource。
        • 遍历获取到的bean,解析bean中的@ComponentScan注解,根据该注解,将包下的bean,转换成BeanDefinition,并放入到BeanDefinitionMap中。
        • 处理类上通过@Import引入的ImportSelector接口的实现类和ImportBeanDefinitionRegistry接口的实现类。
        • 处理@Bean注解引入的bean。
        • 处理@ImportResource注解。
      • 我们需要关心的是对@ComponentScan注解的处理:即parser.parse(candidates)。

        1
        2
        3
        4
        5
        6
        7
        8
        9
        10
        11
        12
        13
        14
        15
        16
        17
        18
        19
        20
        public void parse(Set<BeanDefinitionHolder> configCandidates) {
        for (BeanDefinitionHolder holder : configCandidates) {
        BeanDefinition bd = holder.getBeanDefinition();
        try {
        if (bd instanceof AnnotatedBeanDefinition) {
        parse(((AnnotatedBeanDefinition) bd).getMetadata(), holder.getBeanName());
        }
        …………
        }
        catch (BeanDefinitionStoreException ex) {
        throw ex;
        }
        catch (Throwable ex) {
        throw new BeanDefinitionStoreException(
        "Failed to parse configuration class [" + bd.getBeanClassName() + "]", ex);
        }
        }

        this.deferredImportSelectorHandler.process();
        }
        1
        2
        3
        protected final void parse(AnnotationMetadata metadata, String beanName) throws IOException {
        processConfigurationClass(new ConfigurationClass(metadata, beanName), DEFAULT_EXCLUSION_FILTER);
        }
        1
        2
        3
        4
        5
        6
        7
        8
        9
        10
        11
        protected void processConfigurationClass(ConfigurationClass configClass, Predicate<String> filter) throws IOException {
        …………
        // Recursively process the configuration class and its superclass hierarchy.
        SourceClass sourceClass = asSourceClass(configClass, filter);
        do {
        sourceClass = doProcessConfigurationClass(configClass, sourceClass, filter);
        }
        while (sourceClass != null);

        this.configurationClasses.put(configClass, configClass);
        }
        1
        2
        3
        4
        5
        6
        7
        8
        9
        10
        11
        12
        13
        14
        15
        16
        17
        18
        19
        20
        21
        22
        23
        24
        25
        26
        27
        28
        29
        30
        31
        32
        33
        34
        35
        36
        37
        38
        39
        40
        41
        42
        43
        44
        45
        46
        47
        48
        49
        50
        51
        52
        53
        54
        55
        56
        57
        58
        59
        60
        61
        62
        63
        64
        protected final SourceClass doProcessConfigurationClass(ConfigurationClass configClass, SourceClass sourceClass)
        throws IOException {

        //...省略

        // Process any @ComponentScan annotations
        Set<AnnotationAttributes> componentScans = AnnotationConfigUtils.attributesForRepeatable(
        sourceClass.getMetadata(), ComponentScans.class, ComponentScan.class);
        if (!componentScans.isEmpty() &&
        !this.conditionEvaluator.shouldSkip(sourceClass.getMetadata(), ConfigurationPhase.REGISTER_BEAN)) {
        for (AnnotationAttributes componentScan : componentScans) {
        // The config class is annotated with @ComponentScan -> perform the scan immediately
        Set<BeanDefinitionHolder> scannedBeanDefinitions =
        this.componentScanParser.parse(componentScan, sourceClass.getMetadata().getClassName());
        // Check the set of scanned definitions for any further config classes and parse recursively if needed
        for (BeanDefinitionHolder holder : scannedBeanDefinitions) {
        BeanDefinition bdCand = holder.getBeanDefinition().getOriginatingBeanDefinition();
        if (bdCand == null) {
        bdCand = holder.getBeanDefinition();
        }
        if (ConfigurationClassUtils.checkConfigurationClassCandidate(bdCand, this.metadataReaderFactory)) {
        parse(bdCand.getBeanClassName(), holder.getBeanName());
        }
        }
        }
        }
        // Process any @Import annotations
        processImports(configClass, sourceClass, getImports(sourceClass), filter, true);

        // Process any @ImportResource annotations
        AnnotationAttributes importResource =
        AnnotationConfigUtils.attributesFor(sourceClass.getMetadata(), ImportResource.class);
        if (importResource != null) {
        String[] resources = importResource.getStringArray("locations");
        Class<? extends BeanDefinitionReader> readerClass = importResource.getClass("reader");
        for (String resource : resources) {
        String resolvedResource = this.environment.resolveRequiredPlaceholders(resource);
        configClass.addImportedResource(resolvedResource, readerClass);
        }
        }

        // Process individual @Bean methods
        Set<MethodMetadata> beanMethods = retrieveBeanMethodMetadata(sourceClass);
        for (MethodMetadata methodMetadata : beanMethods) {
        configClass.addBeanMethod(new BeanMethod(methodMetadata, configClass));
        }

        // Process default methods on interfaces
        processInterfaces(configClass, sourceClass);

        // Process superclass, if any
        if (sourceClass.getMetadata().hasSuperClass()) {
        String superclass = sourceClass.getMetadata().getSuperClassName();
        if (superclass != null && !superclass.startsWith("java") &&
        !this.knownSuperclasses.containsKey(superclass)) {
        this.knownSuperclasses.put(superclass, configClass);
        // Superclass found, return its annotation metadata and recurse
        return sourceClass.getSuperClass();
        }
        }

        // No superclass -> processing is complete
        return null;
        }

        这里会解析ComponentScans和ComponentScan注解,ComponentScans是多个ComponentScan的组合,开发中很少使用,我们重点分析ComponentScan,this.conditionEvaluator.shouldSkip是解析时检查一些依赖信息,这里之所以用了for循环解析,是因为可能会解析出多处ComponentScan标注信息,继续看ComponentScanAnnotationParser#parse方法,核心的思想是,从beanDefinition中,获取到componentScan注解的basePackages,即:要扫描的包信息。

        1
        2
        3
        4
        5
        6
        7
        8
        9
        10
        11
        12
        13
        14
        15
        16
        17
        18
        19
        20
        21
        22
        23
        public Set<BeanDefinitionHolder> parse(AnnotationAttributes componentScan, final String declaringClass) {
        //这里的scanner就是spring自己new出来的,用来扫描包的scanner
        //在AnnotaitonConfigApplicationContext的构造方法中,也会初始化一个ClassPathBeanDefinitionScanner();spring在扫描bean的时候,也会初始化一个,和构造方法中,初始化的不是同一个,这里的代码就可以验证这个结论
        //然后解析@ComponentScan注解的属性配到类扫描器中,包括useDefaultFilters、basePackages、includeFilters和excludeFilters等
        ClassPathBeanDefinitionScanner scanner = new ClassPathBeanDefinitionScanner(this.registry,
        componentScan.getBoolean("useDefaultFilters"), this.environment, this.resourceLoader);

        .......
        //如果@ComponentScan注解上的basePackages为空,则默认扫描当前扫描类所在包下所有的类及其子包中的类
        if (basePackages.isEmpty()) {
        basePackages.add(ClassUtils.getPackageName(declaringClass));
        }
        scanner.addExcludeFilter(new AbstractTypeHierarchyTraversingFilter(false, false) {
        @Override
        protected boolean matchClassName(String className) {
        return declaringClass.equals(className);
        }
        });
        /**
        * 如果将bean存入到beanDefinitionMap第七步
        */
        return scanner.doScan(StringUtils.toStringArray(basePackages));
        }
        1
        2
        3
        4
        5
        6
        7
        8
        9
        10
        11
        12
        13
        14
        15
        16
        17
        18
        19
        20
        21
        22
        23
        24
        25
        26
        27
        28
        29
        30
        31
        32
        33
        34
        35
        36
        37
        38
        protected Set<BeanDefinitionHolder> doScan(String... basePackages) {
        Assert.notEmpty(basePackages, "At least one base package must be specified");
        // 初始化容器
        Set<BeanDefinitionHolder> beanDefinitions = new LinkedHashSet<>();
        for (String basePackage : basePackages) {
        // 根据路径扫描,获取BeanDefinition,这个BeanDefinition是ScannedGenericBeanDefinition。默认Component、ManagedBean、Named注解会被扫描进来,其中ManagedBean是JSR-250规范,Named是JSR-330规范,都需要额度的jar包支持。
        // register的conditionEvaluator判断@Conditional注解也是在这里判断。
        Set<BeanDefinition> candidates = findCandidateComponents(basePackage);
        for (BeanDefinition candidate : candidates) {
        // 解析bean的作用域,scope,没有设置默认单例
        ScopeMetadata scopeMetadata = this.scopeMetadataResolver.resolveScopeMetadata(candidate);
        candidate.setScope(scopeMetadata.getScopeName());
        // 解析bean的名称
        String beanName = this.beanNameGenerator.generateBeanName(candidate, this.registry);
        // 设置默认的属性,比如lazy属性是false,还有autowireMode、dependencyCheck、initMethodName、destroyMethodName、enforceInitMethod、enforceDestroyMethod这几个属性设置
        if (candidate instanceof AbstractBeanDefinition) {
        postProcessBeanDefinition((AbstractBeanDefinition) candidate, beanName);
        }
        // 如果是注解的话,设置abd的Lazy, primary DependsOn, Role ,Description这五个属性
        if (candidate instanceof AnnotatedBeanDefinition) {
        AnnotationConfigUtils.processCommonDefinitionAnnotations((AnnotatedBeanDefinition) candidate);
        }
        // 检查beanName如果没注册过,返回false。如果注册过了,要看是否兼容,如果不兼容,抛异常,如果兼容,这边不在注册。
        if (checkCandidate(beanName, candidate)) {
        // 定义一个BeanDefinitionHolder,就是beanName和BeanDefinition的映射
        BeanDefinitionHolder definitionHolder = new BeanDefinitionHolder(candidate, beanName);
        // 是否有代理
        definitionHolder =
        AnnotationConfigUtils.applyScopedProxyMode(scopeMetadata, definitionHolder, this.registry);
        // 加入到beanDefinitions
        beanDefinitions.add(definitionHolder);
        // 往容器注册BeanDefinition(this.beanDefinitionMap.put(beanName, beanDefinition)),同时注册别名
        registerBeanDefinition(definitionHolder, this.registry);
        }
        }
        }
        return beanDefinitions;
        }

        我们要关注的是第一步这里:findCandidateComponents(basePackage)
        这个方法中,就是完成了真正的所谓的自动扫描。

        1
        2
        3
        4
        5
        6
        7
        8
        public Set<BeanDefinition> findCandidateComponents(String basePackage) {
        if (this.componentsIndex != null && indexSupportsIncludeFilters()) {
        return addCandidateComponentsFromIndex(this.componentsIndex, basePackage);
        }
        else {
        return scanCandidateComponents(basePackage);
        }
        }
        1
        2
        3
        4
        5
        6
        7
        8
        9
        10
        11
        12
        13
        14
        15
        16
        17
        18
        19
        20
        21
        22
        23
        24
        25
        26
        27
        28
        29
        30
        31
        32
        33
        34
        35
        36
        37
        38
        39
        40
        41
        42
        43
        44
        45
        46
        47
        48
        49
        50
        51
        52
        53
        54
        private Set<BeanDefinition> scanCandidateComponents(String basePackage) {
        Set<BeanDefinition> candidates = new LinkedHashSet<>();
        try {
        String packageSearchPath = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX +
        resolveBasePackage(basePackage) + '/' + this.resourcePattern;
        Resource[] resources = getResourcePatternResolver().getResources(packageSearchPath);
        boolean traceEnabled = logger.isTraceEnabled();
        boolean debugEnabled = logger.isDebugEnabled();
        for (Resource resource : resources) {
        if (traceEnabled) {
        logger.trace("Scanning " + resource);
        }
        // 判断文件是否可读:这里百度的结果是:如果返回true,不一定可读,但是如果返回false,一定不可读
        if (resource.isReadable()) {
        try {
        MetadataReader metadataReader = getMetadataReaderFactory().getMetadataReader(resource);
        /**
        * isCandidateComponent 也是扫描bean中一个比较核心的方法吧
        * 由于这里的resource是包下所有的class文件,所以,需要在这个方法中判断是否符合注入条件
        *
        * 在AnnatationConfigApplication构造函数中,初始化了一个ClassPathBeanDefinitionScanner;
        * 在初始化这个bean的时候,给一个list中存入了三个类,其中有一个就是Component.class,个人理解:在这个方法中,会
        * 判断扫描出来的class文件是否有Component注解;需要注意的是@Controller @Service @Repository都是被@Component注解修饰的
        * 所以,@Controller... 这些注解修饰的bean也会被注入到spring容器中
        *
        * excludeFilter是在doScan()方法中赋值的,excludeFilter中包含的是当前配置类的beanClassName;因为当前配置类已经存在于beanDefinitionMap中,无需再次添加
        */
        //这个方法是在未生成beanDefinition对象之前,从includeFilter和excludeFilter中进行过滤
        if (isCandidateComponent(metadataReader)) {
        ScannedGenericBeanDefinition sbd = new ScannedGenericBeanDefinition(metadataReader);
        sbd.setResource(resource);
        sbd.setSource(resource);
        /**
        * 对scannedGenericBeanDefinition进行判断
        */
        //是在生成beanDefinition对象之后,判断当前bean是否满足注入的要求
        if (isCandidateComponent(sbd)) {
        if (debugEnabled) {
        logger.debug("Identified candidate component class: " + resource);
        }
        candidates.add(sbd);
        }
        }
        } catch (Throwable ex) {
        throw new BeanDefinitionStoreException(
        "Failed to read candidate component class: " + resource, ex);
        }
        }
        }
        } catch (IOException ex) {
        throw new BeanDefinitionStoreException("I/O failure during classpath scanning", ex);
        }
        return candidates;
        }

        需要注意的是:这里有两个isCandidateComponent方法,但是完成的功能不同。

        • isCandidateComponent(metadataReader):这个方法是在未生成beanDefinition对象之前,从includeFilter和excludeFilter中进行过滤。

          1
          2
          3
          4
          5
          6
          7
          8
          9
          10
          11
          12
          13
          protected boolean isCandidateComponent(MetadataReader metadataReader) throws IOException {
          for (TypeFilter tf : this.excludeFilters) {
          if (tf.match(metadataReader, getMetadataReaderFactory())) {
          return false;
          }
          }
          for (TypeFilter tf : this.includeFilters) {
          if (tf.match(metadataReader, getMetadataReaderFactory())) {
          return isConditionMatch(metadataReader);
          }
          }
          return false;
          }
        • isCandidateComponent(sbd):是在生成beanDefinition对象之后,判断当前bean是否满足注入的要求。

          1
          2
          3
          4
          5
          6
          7
          8
          9
          10
          11
          12
          13
          protected boolean isCandidateComponent(AnnotatedBeanDefinition beanDefinition) {
          AnnotationMetadata metadata = beanDefinition.getMetadata();
          /**
          * spring在扫描普通bean,是用的这个方法,mybatis对该方法进行了扩展,mybatis判断一个beanDefinition是否要放到beanDefinitionMap中,是判断当前是否是接口,是否是顶级类(org.mybatis.spring.mapper.ClassPathMapperScanner#isCandidateComponent)
          *
          * isIndependent:当前类是否独立(顶级类或者嵌套类)
          * isConcrete: 不是接口,不是抽象类,就返回true
          * 如果bean是抽象类,且添加了@LookUp注解,也可以注入
          * 使用抽象类+@LookUp注解,可以解决单实例bean依赖原型bean的问题,这里在spring官方文档中应该也有说明
          */
          return (metadata.isIndependent() && (metadata.isConcrete() ||
          (metadata.isAbstract() && metadata.hasAnnotatedMethods(Lookup.class.getName()))));
          }
  • 打断点进入AbstractApplicationContext.registerBeanPostProcessors(beanFactory)方法,即注册BeanPostProcessor(Bean的后置处理器)。例如:DestructionAwareBeanPostProcessor、InstantiationAwareBeanPostProcessor、SmartInstantiationAwareBeanPostProcessor、MergedBeanDefinitionPostProcessor【放在List<BeanPostProcessor> internalPostProcessors】。不同接口类型的BeanPostProcessor,在Bean创建前后的执行时机是不一样的,主要用在bean实例化之后,执行初始化方法前后允许开发者对bean实例进行修改,Spring中的bean后置处理器继承关系如下图:

    1
    2
    3
    protected void registerBeanPostProcessors(ConfigurableListableBeanFactory beanFactory) {
    PostProcessorRegistrationDelegate.registerBeanPostProcessors(beanFactory, this);
    }
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    public static void registerBeanPostProcessors(
    ConfigurableListableBeanFactory beanFactory, AbstractApplicationContext applicationContext) {
    //获取所有实现BeanPostProcessor的className
    String[] postProcessorNames = beanFactory.getBeanNamesForType(BeanPostProcessor.class, true, false);

    // Register BeanPostProcessorChecker that logs an info message when
    // a bean is created during BeanPostProcessor instantiation, i.e. when
    // a bean is not eligible for getting processed by all BeanPostProcessors.
    //计算出所有beanProcessor的数量
    int beanProcessorTargetCount = beanFactory.getBeanPostProcessorCount() + 1 + postProcessorNames.length;
    //添加BeanPostProcessorChecker(主要用于记录信息)到beanFactory中
    beanFactory.addBeanPostProcessor(new BeanPostProcessorChecker(beanFactory, beanProcessorTargetCount));

    // Separate between BeanPostProcessors that implement PriorityOrdered,
    // Ordered, and the rest.
    //按优先级分类
    List<BeanPostProcessor> priorityOrderedPostProcessors = new ArrayList<>();
    List<BeanPostProcessor> internalPostProcessors = new ArrayList<>();
    List<String> orderedPostProcessorNames = new ArrayList<>();
    List<String> nonOrderedPostProcessorNames = new ArrayList<>();
    for (String ppName : postProcessorNames) {
    if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
    BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
    priorityOrderedPostProcessors.add(pp);
    if (pp instanceof MergedBeanDefinitionPostProcessor) {
    internalPostProcessors.add(pp);
    }
    }
    else if (beanFactory.isTypeMatch(ppName, Ordered.class)) {
    orderedPostProcessorNames.add(ppName);
    }
    else {
    nonOrderedPostProcessorNames.add(ppName);
    }
    }

    // First, register the BeanPostProcessors that implement PriorityOrdered.
    //先注册实现PriorityOrdered接口的处理器,添加到beanfactory容器中。beanFactory.addBeanPostProcessor(postProcessor)。
    sortPostProcessors(priorityOrderedPostProcessors, beanFactory);
    registerBeanPostProcessors(beanFactory, priorityOrderedPostProcessors);

    // Next, register the BeanPostProcessors that implement Ordered.
    //注册实现Ordered接口的处理器。
    List<BeanPostProcessor> orderedPostProcessors = new ArrayList<>(orderedPostProcessorNames.size());
    for (String ppName : orderedPostProcessorNames) {
    BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
    orderedPostProcessors.add(pp);
    if (pp instanceof MergedBeanDefinitionPostProcessor) {
    internalPostProcessors.add(pp);
    }
    }
    sortPostProcessors(orderedPostProcessors, beanFactory);
    registerBeanPostProcessors(beanFactory, orderedPostProcessors);

    // Now, register all regular BeanPostProcessors.
    //注册没有实现Ordered或PriorityOrdered的处理器(nonOrderedPostProcessors)。
    List<BeanPostProcessor> nonOrderedPostProcessors = new ArrayList<>(nonOrderedPostProcessorNames.size());
    for (String ppName : nonOrderedPostProcessorNames) {
    BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
    nonOrderedPostProcessors.add(pp);
    if (pp instanceof MergedBeanDefinitionPostProcessor) {
    internalPostProcessors.add(pp);
    }
    }
    registerBeanPostProcessors(beanFactory, nonOrderedPostProcessors);

    // Finally, re-register all internal BeanPostProcessors.
    //注册MergedBeanDefinitionPostProcessor。
    sortPostProcessors(internalPostProcessors, beanFactory);
    registerBeanPostProcessors(beanFactory, internalPostProcessors);

    // Re-register post-processor for detecting inner beans as ApplicationListeners,
    // moving it to the end of the processor chain (for picking up proxies etc).
    //注册一个后置处理器ApplicationListenerDetector,其用来监听某个bean是不是监听器。如果是则applicationContext.addApplicationListener((ApplicationListener<?>) bean)。
    beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(applicationContext));
    }
    1
    2
    3
    4
    5
    6
    7
    private static void registerBeanPostProcessors(
    ConfigurableListableBeanFactory beanFactory, List<BeanPostProcessor> postProcessors) {

    for (BeanPostProcessor postProcessor : postProcessors) {
    beanFactory.addBeanPostProcessor(postProcessor);
    }
    }
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    @Override
    public void addBeanPostProcessor(BeanPostProcessor beanPostProcessor) {
    Assert.notNull(beanPostProcessor, "BeanPostProcessor must not be null");
    // Remove from old position, if any
    //如果beanPostProcessor已经存在则移除(可以起到排序的效果,beanPostProcessor可能本来在前面,移除再添加,则变到最后面)
    this.beanPostProcessors.remove(beanPostProcessor);
    // Track whether it is instantiation/destruction aware
    if (beanPostProcessor instanceof InstantiationAwareBeanPostProcessor) {
    //如果beanPostProcessor是InstantiationAwareBeanPostProcessor, 则将hasInstantiationAwareBeanPostProcessors设置为true,该变量用于指示beanFactory是否已注册过InstantiationAwareBeanPostProcessors
    this.hasInstantiationAwareBeanPostProcessors = true;
    }
    if (beanPostProcessor instanceof DestructionAwareBeanPostProcessor) {
    //如果beanPostProcessor是DestructionAwareBeanPostProcessor, 则将hasInstantiationAwareBeanPostProcessors设置为true,该变量用于指示beanFactory是否已注册过DestructionAwareBeanPostProcessor
    this.hasDestructionAwareBeanPostProcessors = true;
    }
    // Add to end of list
    //将beanPostProcessor添加到beanPostProcessors缓存
    this.beanPostProcessors.add(beanPostProcessor);
    }
    • ①初始化存放Processor集合。

    • ②将所有BeanPostProcessor分门别类放进各个集合。

      • 遍历所有实现BeanPostProcessor的实现类className。
      • 如果含有@PriorityOrdered注解的实现类,把对应的PostProcessor放入到priorityOrderedPostProcessors。
      • 如果含有@Ordered注解的实现类,把对应的className放入到orderedPostProcessorNames。
      • 把不包含排序注解的实现类,把对应的className放入到nonOrderedPostProcessorNames。
    • ③将实现了PriorityOrdered优先级接口的BeanPostProcessor进行排序并注册(把每一个BeanPostProcessor添加到BeanFactory中,beanFactory.addBeanPostProcessor(postProcessor))。如果ppName对应的Bean实例也实现了MergedBeanDefinitionPostProcessor接口,则将ppName对应的Bean实例添加到internalPostProcessors中。

    • ④将实现了Ordered优先级接口的BeanPostProcessor进行排序并注册(把每一个BeanPostProcessor添加到BeanFactory中,beanFactory.addBeanPostProcessor(postProcessor))。如果ppName对应的Bean实例也实现了MergedBeanDefinitionPostProcessor接口,则将ppName对应的Bean实例添加到internalPostProcessors中。

    • ⑤最后注册没有实现任何优先级接口的BeanPostProcessor(把每一个BeanPostProcessor添加到BeanFactory中,beanFactory.addBeanPostProcessor(postProcessor))。如果ppName对应的Bean实例也实现了MergedBeanDefinitionPostProcessor接口,则将ppName对应的Bean实例添加到internalPostProcessors中。

    • ⑥对所有的MergedBeanDefinitionPostProcessor进行排序并注册(把每一个BeanPostProcessor添加到BeanFactory中,beanFactory.addBeanPostProcessor(postProcessor))。

    • ⑦注册一个后置处理器ApplicationListenerDetector,其用来监听某个bean是不是监听器。在Bean初始化完成之后,如果Bean是单例的则并且bean instanceof ApplicationListener则加入到this.applicationListeners中(this.applicationContext.addApplicationListener((ApplicationListener<?>) bean));在Bean销毁之前,如果Bean是一个ApplicationListener,则会从ApplicationEventMulticaster(事件广播器)中提前删除。

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      16
      17
      18
      19
      20
      21
      22
      23
      24
      25
      26
      27
      28
      29
      30
      31
      32
      33
      34
      35
      36
      37
      38
      39
      40
      41
      42
      class ApplicationListenerDetector implements DestructionAwareBeanPostProcessor, MergedBeanDefinitionPostProcessor {
      …………
      //初始化之前
      @Override
      public Object postProcessAfterInitialization(Object bean, String beanName) {
      if (bean instanceof ApplicationListener) {
      // potentially not detected as a listener by getBeanNamesForType retrieval
      Boolean flag = this.singletonNames.get(beanName);
      if (Boolean.TRUE.equals(flag)) {
      // singleton bean (top-level or inner): register on the fly
      this.applicationContext.addApplicationListener((ApplicationListener<?>) bean);
      }
      else if (Boolean.FALSE.equals(flag)) {
      if (logger.isWarnEnabled() && !this.applicationContext.containsBean(beanName)) {
      // inner bean with other scope - can't reliably process events
      logger.warn("Inner bean '" + beanName + "' implements ApplicationListener interface " +
      "but is not reachable for event multicasting by its containing ApplicationContext " +
      "because it does not have singleton scope. Only top-level listener beans are allowed " +
      "to be of non-singleton scope.");
      }
      this.singletonNames.remove(beanName);
      }
      }
      return bean;
      }

      //销毁之前
      @Override
      public void postProcessBeforeDestruction(Object bean, String beanName) {
      if (bean instanceof ApplicationListener) {
      try {
      ApplicationEventMulticaster multicaster = this.applicationContext.getApplicationEventMulticaster();
      multicaster.removeApplicationListener((ApplicationListener<?>) bean);
      multicaster.removeApplicationListenerBean(beanName);
      }
      catch (IllegalStateException ex) {
      // ApplicationEventMulticaster not initialized yet - no need to remove a listener
      }
      }
      }
      …………
      }
  • **打断点进入AbstractApplicationContext.initMessageSource()**,用来设置国际化资源相关的调用,将实现了MessageSource接口的bean存放在ApplicationContext的成员变量中,先看是否有此配置,如果有就实例化,否则就创建一个DelegatingMessageSource实例的bean。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    protected void initMessageSource() {
    //获取BeanFactory。
    ConfigurableListableBeanFactory beanFactory = getBeanFactory();
    //看容器中是否有id为messageSource的,类型是MessageSource的组件,如果有赋值给messageSource,如果没有自己创建一个DelegatingMessageSource。
    if (beanFactory.containsLocalBean(MESSAGE_SOURCE_BEAN_NAME)) {
    this.messageSource = beanFactory.getBean(MESSAGE_SOURCE_BEAN_NAME, MessageSource.class);
    // Make MessageSource aware of parent MessageSource.
    if (this.parent != null && this.messageSource instanceof HierarchicalMessageSource) {
    HierarchicalMessageSource hms = (HierarchicalMessageSource) this.messageSource;
    if (hms.getParentMessageSource() == null) {
    // Only set parent context as parent MessageSource if no parent MessageSource
    // registered already.
    //如果已经注册的父上下文没有消息源,则只能将父上下文设置为父消息源
    hms.setParentMessageSource(getInternalParentMessageSource());
    }
    }
    if (logger.isTraceEnabled()) {
    logger.trace("Using MessageSource [" + this.messageSource + "]");
    }
    }
    else {
    // Use empty MessageSource to be able to accept getMessage calls.
    DelegatingMessageSource dms = new DelegatingMessageSource();
    dms.setParentMessageSource(getInternalParentMessageSource());
    this.messageSource = dms;
    //将messageSource注册进容器中,以后可以通过自动注入方式来使用。
    beanFactory.registerSingleton(MESSAGE_SOURCE_BEAN_NAME, this.messageSource);
    if (logger.isTraceEnabled()) {
    logger.trace("No '" + MESSAGE_SOURCE_BEAN_NAME + "' bean, using [" + this.messageSource + "]");
    }
    }
    }
    • ①获取BeanFactory。
    • ②看容器中是否有id为messageSource的,类型是MessageSource的组件,如果有赋值给messageSource,如果没有自己创建一个DelegatingMessageSource。(MessageSource:取出国际化配置文件中的某个key的值;能按照区域信息获取),messageSource的继承关系如图:
    • ③把创建好的MessageSource注册在容器中,以后获取国际化配置文件的值的时候,可以自动注入MessageSource。(使用即MessageSource.getMessage(String code, Object[] args, String defaultMessage, Locale locale))
  • 打断点进入AbstractApplicationContext.initApplicationEventMulticaster()方法,即初始化并注册事件派发器。Spring的监听器机制包含事件、事件发布者、事件监听器:

    • 事件:ApplicationEvent,要自定义事件,则需要创建一个类继承 ApplicationEvent。
    • 事件发布者:ApplicationEventPublisher和ApplicationEventMulticaster,因为ApplicationContext实现了ApplicationEventPublisher,所以事件发布可以直接使用ApplicationContext。
    • 事件监听器:ApplicationListener,通过创建一个实现了ApplicationListener并注册为Spring bean的类来接收消息。
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    protected void initApplicationEventMulticaster() {
    //获取BeanFactory。
    ConfigurableListableBeanFactory beanFactory = getBeanFactory();
    //从BeanFactory中获取applicationEventMulticaster的ApplicationEventMulticaster,若没有则创建一个SimpleApplicationEventMulticaster。
    if (beanFactory.containsLocalBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME)) {
    this.applicationEventMulticaster =
    beanFactory.getBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, ApplicationEventMulticaster.class);
    if (logger.isTraceEnabled()) {
    logger.trace("Using ApplicationEventMulticaster [" + this.applicationEventMulticaster + "]");
    }
    }
    else {
    this.applicationEventMulticaster = new SimpleApplicationEventMulticaster(beanFactory);
    //将创建的ApplicationEventMulticaster添加到BeanFactory中。
    beanFactory.registerSingleton(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, this.applicationEventMulticaster);
    if (logger.isTraceEnabled()) {
    logger.trace("No '" + APPLICATION_EVENT_MULTICASTER_BEAN_NAME + "' bean, using " +
    "[" + this.applicationEventMulticaster.getClass().getSimpleName() + "]");
    }
    }
    }
    • ①获取BeanFactory。
    • ②从BeanFactory中获取applicationEventMulticaster的ApplicationEventMulticaster,若没有则创建一个SimpleApplicationEventMulticaster。
    • ③将创建的ApplicationEventMulticaster添加到BeanFactory中,以后其他组件直接自动注入。
  • 打断点进入AbstractApplicationContext.onRefresh()方法,是个空方法,即子类可以重写这个方法,在容器刷新的时候可以自定义逻辑。

    1
    2
    3
    protected void onRefresh() throws BeansException {
    // For subclasses: do nothing by default.
    }
  • 打断点进入AbstractApplicationContext.registerListeners()方法,即将所有项目里面的ApplicationListener注册进容器。只是将一些特殊的监听器注册到广播组中,那些在bean配置文件中实现了ApplicationListener接口的类还没有实例化,所以此时只是将listenerBeanNames保存到了广播组中,将这些监听器注册到广播组中的操作时在bean的后置处理器中完成的,那时候bean的实例化已经完成了。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    protected void registerListeners() {
    // Register statically specified listeners first.
    //首先注册静态的指定的监听器,注册的是特殊的事件监听器,而不是配置中的bean
    for (ApplicationListener<?> listener : getApplicationListeners()) {
    getApplicationEventMulticaster().addApplicationListener(listener);
    }

    // Do not initialize FactoryBeans here: We need to leave all regular beans
    // uninitialized to let post-processors apply to them!
    //从容器中拿到所有的ApplicationListener的beanNames。
    //这里不会初始化FactoryBean,我们需要保留所有的普通bean
    //不会实例化这些bean,让后置处理器能够感知到它们
    String[] listenerBeanNames = getBeanNamesForType(ApplicationListener.class, true, false);
    //将每个监听器添加到事件派发器中。
    for (String listenerBeanName : listenerBeanNames) {
    getApplicationEventMulticaster().addApplicationListenerBean(listenerBeanName);
    }

    // Publish early application events now that we finally have a multicaster...
    //现在有了事件广播组,发布之前的应用事件
    Set<ApplicationEvent> earlyEventsToProcess = this.earlyApplicationEvents;
    this.earlyApplicationEvents = null;
    if (earlyEventsToProcess != null) {
    for (ApplicationEvent earlyEvent : earlyEventsToProcess) {
    getApplicationEventMulticaster().multicastEvent(earlyEvent);
    }
    }
    }
    • ①从容器中拿到所有的ApplicationListener。
    • ②将每个监听器添加到事件派发器中。
    • ③派发之前步骤产生的事件。
  • 打断点进入AbstractApplicationContext.finishBeanFactoryInitialization(beanFactory)方法,即初始化所有剩下的单实例bean。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    protected void finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory) {
    // Initialize conversion service for this context.
    //组件转换器相关
    //初始化此上下文的转换服务,例如ConversionService的实现类DefaultConversionService在addDefaultConverters方法中就准备了好几种类型转换的转换器
    if (beanFactory.containsBean(CONVERSION_SERVICE_BEAN_NAME) &&
    beanFactory.isTypeMatch(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class)) {
    beanFactory.setConversionService(
    beanFactory.getBean(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class));
    }

    // Register a default embedded value resolver if no bean post-processor
    // (such as a PropertyPlaceholderConfigurer bean) registered any before:
    // at this point, primarily for resolution in annotation attribute values.
    //判断BeanFactory是否有解析器。如果没有的话,给他添加个默认解析器
    if (!beanFactory.hasEmbeddedValueResolver()) {
    beanFactory.addEmbeddedValueResolver(strVal -> getEnvironment().resolvePlaceholders(strVal));
    }

    // Initialize LoadTimeWeaverAware beans early to allow for registering their transformers early.
    //aspectj相关,在这里去获取LoadTimeWeaverAware的实现类的className
    String[] weaverAwareNames = beanFactory.getBeanNamesForType(LoadTimeWeaverAware.class, false, false);
    for (String weaverAwareName : weaverAwareNames) {
    getBean(weaverAwareName);
    }

    // Stop using the temporary ClassLoader for type matching.
    //设置模版加载器为null
    beanFactory.setTempClassLoader(null);

    // Allow for caching all bean definition metadata, not expecting further changes.
    //冻结配置,防止beanDefinitionNames在进行实例化的时候发生改变
    beanFactory.freezeConfiguration();

    // Instantiate all remaining (non-lazy-init) singletons.
    // 初始化剩下的单实例bean。
    beanFactory.preInstantiateSingletons();
    }

    重点是执行DefaultListableBeanFactory类中的preInstantiateSingletons()方法初始化剩下的单实例bean。

    • ①获取容器中的所有Bean。

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      @Override
      public void preInstantiateSingletons() throws BeansException {
      if (logger.isTraceEnabled()) {
      logger.trace("Pre-instantiating singletons in " + this);
      }

      // Iterate over a copy to allow for init methods which in turn register new bean definitions.
      // While this may not be part of the regular factory bootstrap, it does otherwise work fine.
      //获取所有的beanDefinitionNames
      List<String> beanNames = new ArrayList<>(this.beanDefinitionNames);
    • ②获取Bean的定义信息:RootBeanDefinition。

      1
      2
      //根据beanDefinitionNames根据父节点和节点进行组装为整体的RootBeanDefinition
      RootBeanDefinition bd = getMergedLocalBeanDefinition(beanName);
      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      protected RootBeanDefinition getMergedLocalBeanDefinition(String beanName) throws BeansException {
      // Quick check on the concurrent map first, with minimal locking.
      //先从缓存里面进行获取,看是否存在,如果不存在才进行merge
      //在之前的invokeBeanFactoryPostProcessors(beanFactory)->PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors->beanFactory.getBeanNamesForType()->doGetBeanNamesForType()方法中已经执行getMergedLocalBeanDefinition()在查询缓存为null时加入缓存
      RootBeanDefinition mbd = this.mergedBeanDefinitions.get(beanName);
      if (mbd != null && !mbd.stale) {
      return mbd;
      }
      return getMergedBeanDefinition(beanName, getBeanDefinition(beanName));
      }
    • ③判断Bean判断是否非抽象,单例,非延迟加载。

      1
      if (!bd.isAbstract() && bd.isSingleton() && !bd.isLazyInit()) {
      • ①判断是否是FactoryBean,即是否是实现FactoryBean接口的Bean。如果使用BeanFactory接口。那么必须严格遵守SpringBean的生命周期。从实例化到初始化到before和after。此流程很复杂且麻烦。需要一种更加便捷简单的方式创建,所以有了FactoryBean,它不需要遵循此创建顺序。

        1
        2
        3
        4
        5
        6
        7
        8
        9
        10
        11
        12
        13
        14
        15
        16
        17
        18
        19
        20
        21
        22
        if (isFactoryBean(beanName)) {
        //获取FactoryBean的方式就是前缀+beanName
        Object bean = getBean(FACTORY_BEAN_PREFIX + beanName);
        //判断是否FactoryBean
        if (bean instanceof FactoryBean) {
        final FactoryBean<?> factory = (FactoryBean<?>) bean;
        boolean isEagerInit;
        if (System.getSecurityManager() != null && factory instanceof SmartFactoryBean) {
        isEagerInit = AccessController.doPrivileged((PrivilegedAction<Boolean>)
        ((SmartFactoryBean<?>) factory)::isEagerInit,
        getAccessControlContext());
        }
        else {
        //判断是不是SmartFactoryBean这个类型的,如果是就去创建SmartFactoryBean属于FactoryBean子接口,拥有更加细粒度操作原数据的方式
        isEagerInit = (factory instanceof SmartFactoryBean &&
        ((SmartFactoryBean<?>) factory).isEagerInit());
        }
        if (isEagerInit) {
        getBean(beanName);
        }
        }
        }
      • ②如果不是工厂Bean。利用getBean(beanName)创建对象:

        1
        2
        3
        4
        else {
        //AbstractBeanFactory.getBean(beanName)
        getBean(beanName);
        }
        1
        2
        3
        4
        5
        @Override
        public Object getBean(String name) throws BeansException {
        //AbstractBeanFactory.doGetBean(name, null, null, false)
        return doGetBean(name, null, null, false);
        }
        • ①执行transformedBeanName()方法,该方法将doGetBean的参数name转换成容器中真实的beanName(获取容器中真实beanName)(传递过来的name有三种可能,一个是原始的beanName,一个是加了&的,一个是别名。所以我们要统一将其转换 ) 。

          1
          2
          3
          //通过三种形式获取beanName
          //一个是原始的beanName,一个是加了&的,一个是别名
          final String beanName = transformedBeanName(name);
        • ②执行getSingleton()方法,该方法将尝试从单例缓存集合里获取bean实例。 尝试从一级缓存(singletonObjects)中获取完备的Bean,如果没有则尝试从二级缓存earlySingletonObjects这个存储还没进行属性添加操作的Bean实例缓存中获取,如果一二级缓存都没有,查看该bean是否允许被循环引用,是则从三级缓存singletonFactories这个ObjectFactory实例的缓存里尝试获取创建此Bean的单例工厂实例,后调用工厂getObject()获取bean实例后存入二级缓存,从三级缓存中移除,返回bean。

          1
          2
          // Eagerly check singleton cache for manually registered singletons.
          Object sharedInstance = getSingleton(beanName);
          1
          2
          3
          4
          5
          @Override
          @Nullable
          public Object getSingleton(String beanName) {
          return getSingleton(beanName, true);
          }
          1
          2
          3
          4
          5
          6
          7
          8
          9
          10
          11
          12
          13
          14
          15
          16
          17
          18
          19
          20
          21
          22
          23
          24
          25
          26
          27
          28
          @Nullable
          protected Object getSingleton(String beanName, boolean allowEarlyReference) {
          //从单例对象缓存中获取beanName对应的单例对象
          Object singletonObject = this.singletonObjects.get(beanName);
          //如果单例对象缓存中没有,并且该beanName对应的单例bean正在创建中
          if (singletonObject == null && isSingletonCurrentlyInCreation(beanName)) {
          //如果为空,则锁定全局变量并进行处理
          synchronized (this.singletonObjects) {
          //从早期单例对象缓存(二级缓存)中获取单例对象(之所称成为早期单例对象,是因为earlySingletonObject里的对象的都是通过提前曝光的ObjectFactory创建出来的,还未进行属性填充等操作)
          singletonObject = this.earlySingletonObjects.get(beanName);
          //如果在早期单例对象缓存中也没有,并且允许创建早期单例对象引用
          if (singletonObject == null && allowEarlyReference) {
          //从三级缓存中根据beanName获取单例工厂
          ObjectFactory<?> singletonFactory = this.singletonFactories.get(beanName);
          //如果从三级缓存中获取到单例工厂
          if (singletonFactory != null) {
          //如果存在单例对象工厂,则通过工厂创建一个单例对象
          singletonObject = singletonFactory.getObject();
          //记录在二级缓存中,二级缓存和三级缓存的对象不能同时存在
          this.earlySingletonObjects.put(beanName, singletonObject);
          //从三级缓存中移除
          this.singletonFactories.remove(beanName);
          }
          }
          }
          }
          return singletonObject;
          }
        • ③如果先前已经创建过单例Bean的实例,并且调用的getBean方法传入的参数为空,则执行if里面的逻辑。

          1
          2
          3
          4
          5
          6
          7
          8
          9
          10
          11
          12
          13
          14
          15
          16
          17
          //如果先前已经创建过单例Bean的实例,并且调用的getBean方法传入的参数为空
          //则执行if里面的逻辑
          //args之所以要求为空是因为如果有args,则需要做进一步赋值,因此无法直接返回
          if (sharedInstance != null && args == null) {
          if (logger.isTraceEnabled()) {
          //如果Bean还在创建中,则说明是循环引用
          if (isSingletonCurrentlyInCreation(beanName)) {
          logger.trace("Returning eagerly cached instance of singleton bean '" + beanName +
          "' that is not fully initialized yet - a consequence of a circular reference");
          }
          else {
          logger.trace("Returning cached instance of singleton bean '" + beanName + "'");
          }
          }
          //如果是普通bean,直接返回,如果是FactoryBean,则返回它的getObject
          bean = getObjectForBeanInstance(sharedInstance, name, beanName, null);
          }
        • ④如果缓存中获取不到,开始Bean的创建对象流程。如果scope为prototype并且显示还在创建中,则基本是循环依赖的情况,直接抛出异常。

          1
          2
          3
          4
          5
          6
          7
          8
          // Fail if we're already creating this bean instance:
          // We're assumably within a circular reference.
          //如果scope为prototype并且 显示还在创建中,则基本是循环依赖的情况
          //针对prototype的循环依赖,spring误解,直接抛出异常
          //简单来说Spring不支持原型bean的循环依赖
          if (isPrototypeCurrentlyInCreation(beanName)) {
          throw new BeanCurrentlyInCreationException(beanName);
          }
        • ⑤从当前容器中找不到指定名称的bean,此时递归去parentFactory查找。

          1
          2
          3
          4
          5
          6
          7
          8
          9
          10
          11
          12
          13
          14
          15
          16
          17
          18
          19
          20
          21
          22
          23
          24
          25
          26
          27
          28
          29
          // Check if bean definition exists in this factory.
          BeanFactory parentBeanFactory = getParentBeanFactory();
          //从当前容器中找不到指定名称的bean,此时递归去parentFactory查找
          if (parentBeanFactory != null && !containsBeanDefinition(beanName)) {
          // Not found -> check parent.
          //主要针对FactoryBean,将Bean的&重新加上
          String nameToLookup = originalBeanName(name);
          //如果parent容器依旧是AbstractBeanFactory的实例
          //instanceof通过返回一个布尔值来指出,这个对象是否是这个特定类或者是它的子类的一个实例
          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);
          }
          }
        • ⑥标记当前bean已经被创建。

          1
          2
          3
          4
          5
          //typeCheckOnly是用来判断调用getBean()是否仅仅是为了类型检查获取bean,而不是为了创建Bean
          if (!typeCheckOnly) {
          //如果不是仅仅做类型检查则是创建bean
          markBeanAsCreated(beanName);
          }
        • ⑦获取Bean的定义信息。

          1
          2
          3
          4
          //将父类的BeanDefinition与子类的BeanDefinition进行合并覆盖
          final RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
          //对合并的BeanDefinition做验证,主要看属性是否为abstract的
          checkMergedBeanDefinition(mbd, beanName, args);
        • ⑧获取当前Bean依赖的其他Bean,如果有按照getBean()把依赖的Bean先创建出来。

          1
          2
          3
          4
          5
          6
          7
          8
          9
          10
          11
          12
          13
          14
          15
          16
          17
          18
          19
          20
          21
          22
          23
          24
          25
          26
          27
          28
          29
          30
          31
          // Guarantee initialization of beans that the current bean depends on.
          //获取当前Bean所有依赖Bean的名称
          String[] dependsOn = mbd.getDependsOn();
          //如果当前Bean设置了dependsOn的属性
          //depends-on用来指定Bean初始化及销毁时的顺序
          //<bean id="a" Class="com.imooc.A" depends-on="b" />
          //<bean id="b" Class="com.imooc.B" />
          if (dependsOn != null) {
          for (String dep : dependsOn) {
          //校验该依赖是否已经注册给当前bean,注意这里传入的key是当前的bean名称
          //这里主要是判断是否有以下这种类型的依赖:
          //<bean id="beanA" Class="com.imooc.A" depends-on="beanB" />
          //<bean id="beanB" Class="com.imooc.B" depends-on="beanA" />
          //如果有,直接抛出异常
          if (isDependent(beanName, dep)) {
          throw new BeanCreationException(mbd.getResourceDescription(), beanName,
          "Circular depends-on relationship between '" + beanName + "' and '" + dep + "'");
          }
          //缓存依赖调用,注意这里传入的key是被依赖的bean名称
          registerDependentBean(dep, beanName);
          try {
          //递归调用getBean方法,注册Bean之间的依赖(如C需要晚于B初始化,而B需要晚于A初始化)
          //初始化依赖的bean
          getBean(dep);
          }
          catch (NoSuchBeanDefinitionException ex) {
          throw new BeanCreationException(mbd.getResourceDescription(), beanName,
          "'" + beanName + "' depends on missing bean '" + dep + "'", ex);
          }
          }
          }
        • ⑨启动单实例Bean的创建流程。 在这里需要注意,回调函数createBean(beanName, mbd, args)的调用发生在getSingleton()的singletonFactory.getObject()中。

          1
          2
          3
          4
          5
          6
          7
          8
          9
          10
          11
          12
          13
          14
          15
          16
          17
          18
          19
          20
          21
          22
          // Create bean instance.
          //如果BeanDefinition为单例
          if (mbd.isSingleton()) {
          //这里使用了一个匿名内部类,创建Bean实例对象,并且注册给所依赖的对象
          sharedInstance = getSingleton(beanName, () -> {
          try {
          return createBean(beanName, mbd, args); //**************
          }
          catch (BeansException ex) {
          // Explicitly remove instance from singleton cache: It might have been put there
          // eagerly by the creation process, to allow for circular reference resolution.
          // Also remove any beans that received a temporary reference to the bean.
          //显示从单例缓存中删除bean实例
          //因为单例模式下为了解决循环依赖,可能它已经存在了,所有将其销毁
          destroySingleton(beanName);
          throw ex;
          }
          });
          //如果是普通bean,直接返回,如果是FactoryBean,则返回它的getObject
          bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
          }

          • ①getSingleton方法如下:

            1
            2
            3
            4
            5
            6
            7
            8
            9
            10
            11
            12
            13
            14
            15
            16
            17
            18
            19
            20
            21
            22
            23
            24
            25
            26
            27
            28
            29
            30
            31
            32
            33
            34
            35
            36
            37
            38
            39
            40
            41
            42
            43
            44
            45
            46
            47
            48
            49
            50
            51
            52
            53
            54
            55
            56
            public Object getSingleton(String beanName, ObjectFactory<?> singletonFactory) {
            Assert.notNull(beanName, "Bean name must not be null");
            synchronized (this.singletonObjects) {
            //从一级缓存中判断有没有bean对象
            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 + "'");
            }
            //将beanClass放入到singletonsCurrentlyInCreation容器中,表示正在创建中
            beforeSingletonCreation(beanName);
            boolean newSingleton = false;
            boolean recordSuppressedExceptions = (this.suppressedExceptions == null);
            if (recordSuppressedExceptions) {
            this.suppressedExceptions = new LinkedHashSet<>();
            }
            try {
            //其实是上面讲的回调,此时它调用的实则是createBean方法
            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) {
            //将创建的Bean添加到缓存singletonObjects中,即执行addSingleton(beanName, singletonObject)。(ioc容器就是这些Map,很多的Map里面保存了单实例Bean,环境信息等)
            addSingleton(beanName, singletonObject);
            }
            }
            return singletonObject;
            }
            }
          • ②调用AbstractAutowireCapableBeanFactory.createBean(beanName, mbd, args)。

            1
            2
            3
            4
            5
            6
            7
            8
            9
            10
            11
            12
            13
            14
            15
            16
            17
            18
            19
            20
            21
            22
            23
            24
            25
            26
            27
            28
            29
            30
            31
            32
            33
            34
            35
            36
            37
            38
            39
            40
            41
            42
            43
            44
            45
            46
            47
            48
            49
            50
            51
            52
            53
            54
            55
            56
            57
            58
            59
            @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.
            //此时factorybean 里面的class还是String字符串类型,此时的方法其实就是String 转化为class类型的对象
            Class<?> resolvedClass = resolveBeanClass(mbd, beanName);
            if (resolvedClass != null && !mbd.hasBeanClass() && mbd.getBeanClassName() != null) {
            mbdToUse = new RootBeanDefinition(mbd);
            mbdToUse.setBeanClass(resolvedClass);
            }

            // Prepare method overrides.
            try {
            //参考https://www.cnblogs.com/ViviChan/p/4981619.html
            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.
            //给BeanPostProcessors一个返回代理而不是目标bean实例的机会
            Object bean = resolveBeforeInstantiation(beanName, mbdToUse);
            if (bean != null) {
            return bean;
            }
            }
            catch (Throwable ex) {
            throw new BeanCreationException(mbdToUse.getResourceDescription(), beanName,
            "BeanPostProcessor before instantiation of bean failed", ex);
            }

            try {
            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);
            }
            }
            • ①调用AbstractAutowireCapableBeanFactory.resolveBeforeInstantiation(beanName, mbdToUse),即让BeanPostProcessor【InstantiationAwareBeanPostProcessor】先拦截返回代理对象(此BeanPostProcessor在创建bean之前就提前执行了)。此方法先触发postProcessBeforeInstantiation(),如果有返回值则触发postProcessAfterInitialization()。

              1
              2
              3
              4
              5
              6
              7
              8
              9
              10
              11
              12
              13
              14
              15
              16
              17
              18
              19
              20
              @Nullable
              protected Object resolveBeforeInstantiation(String beanName, RootBeanDefinition mbd) {
              Object bean = null;
              if (!Boolean.FALSE.equals(mbd.beforeInstantiationResolved)) {
              // Make sure bean class is actually resolved at this point.
              if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
              Class<?> targetType = determineTargetType(beanName, mbd);
              if (targetType != null) {
              //先触发postProcessBeforeInstantiation()
              bean = applyBeanPostProcessorsBeforeInstantiation(targetType, beanName);
              //如果有返回值则触发postProcessAfterInitialization()
              if (bean != null) {
              bean = applyBeanPostProcessorsAfterInitialization(bean, beanName);
              }
              }
              }
              mbd.beforeInstantiationResolved = (bean != null);
              }
              return bean;
              }
            • ②如果前面的InstantiationAwareBeanPostProcessor没有返回代理对象,调用AbstractAutowireCapableBeanFactory.doCreateBean(beanName, mbdToUse, args)进入bean的正式创建流程。

              • ①声明包装类,判断对象是否为单例对象,如果是的话,则factorybean的容器中移除掉。

                1
                2
                3
                4
                5
                6
                7
                8
                9
                10
                // Instantiate the bean.
                //声明包装类
                //这里BeanWrapper是一个从BeanDefinition到Bean直接的中间产物,我们可以称它为”低级bean"
                //BeanWrapper是Spring框架中重要的组件类,它就相当于一个代理类,Spring委托BeanWrapper完成Bean属性的填充工作
                //在Bean实例被InstantiationStrategy创建出来后,Spring容器会将Bean实例通过BeanWrapper包裹起来
                BeanWrapper instanceWrapper = null;
                //判断对象是否为单例对象,如果是的话,则factorybean的容器中移除掉
                if (mbd.isSingleton()) {
                instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);
                }
              • ②利用工厂方法或者对象的构造器创建出Bean实例。即调用AbstractAutowireCapableBeanFactory.createBeanInstance(beanName, mbd, args)方法。

                1
                2
                3
                if (instanceWrapper == null) {
                instanceWrapper = createBeanInstance(beanName, mbd, args);
                }
                1
                2
                3
                4
                5
                6
                7
                8
                9
                10
                11
                12
                13
                14
                15
                16
                17
                18
                19
                20
                21
                22
                23
                24
                25
                26
                27
                28
                29
                30
                31
                32
                33
                34
                35
                36
                37
                38
                39
                40
                41
                42
                43
                44
                45
                46
                47
                48
                49
                50
                51
                52
                53
                54
                55
                56
                protected BeanWrapper createBeanInstance(String beanName, RootBeanDefinition mbd, @Nullable Object[] args) {
                // Make sure bean class is actually resolved at this point.
                //将String类型的className转化为Class类型的className,确保此时实际解析了bean类
                Class<?> beanClass = resolveBeanClass(mbd, beanName);
                //确保class不为空,并且访问权限是public
                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());
                }
                //判断当前beanDefinition中是否包含实例供应器,此处相当于一个回调方法,利用回调方法来创建bean
                //factorybean和Supplier创建对象的区别:factorybean抽象出一个接口规范,所有的对象必须通过getObject方法获取,它属于接口规范的实现;Supplier随便定义创建对象的方法,不只局限于getObject,它属于beanDefinition的属性
                Supplier<?> instanceSupplier = mbd.getInstanceSupplier();
                if (instanceSupplier != null) {
                return obtainFromSupplier(instanceSupplier, beanName);
                }
                //通过factoryMethod实例化对象
                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.
                return instantiateBean(beanName, mbd);
                }
              • ③调用AbstractAutowireCapableBeanFactory.applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName)方法,即调用后置处理器MergedBeanDefinitionPostProcessor的postProcessMergedBeanDefinition(mbd, beanType, beanName)方法,这里主要是为了后面填充Bean属性做一些前置准备,比如说@Autowrited@Value@Resource@Lazy等的前置处理工作就是在这个节点上触发的。

                1
                2
                3
                4
                5
                6
                7
                8
                protected void applyMergedBeanDefinitionPostProcessors(RootBeanDefinition mbd, Class<?> beanType, String beanName) {
                for (BeanPostProcessor bp : getBeanPostProcessors()) {
                if (bp instanceof MergedBeanDefinitionPostProcessor) {
                MergedBeanDefinitionPostProcessor bdp = (MergedBeanDefinitionPostProcessor) bp;
                bdp.postProcessMergedBeanDefinition(mbd, beanType, beanName);
                }
                }
                }
              • ③将实例化好的bean包装成单例工厂添加到三级缓存中,这一步主要是处理循环依赖,同时也为我们提供了一个解决方案的切入口。

                1
                2
                3
                4
                5
                6
                7
                8
                9
                10
                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属性赋值】调用AbstractAutowireCapableBeanFactory.populateBean(beanName, mbd, instanceWrapper)方法给Bean属性赋值。

                • ①【赋值前】判断该bean是否进行属性填充。主要是寻找所有实现了InstantiationAwareBeanPostProcessor的实例,并访问其postProcessAfterInstantiation()方法,如果返回的是false这跳过属性填充逻辑。

                  1
                  2
                  3
                  4
                  5
                  6
                  7
                  8
                  9
                  10
                  11
                  12
                  //判断bean是否需要创建
                  if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
                  for (BeanPostProcessor bp : getBeanPostProcessors()) {
                  if (bp instanceof InstantiationAwareBeanPostProcessor) {
                  InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
                  //如果返回false则跳过属性填充逻辑
                  if (!ibp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) {
                  return;
                  }
                  }
                  }
                  }
                • ②【赋值前】访问各个处理器获取PropertyValues(但有些处理器直接进行了填充),通过InstantiationAwareBeanPostProcessor实例的 postProcessProperties()方法或postProcessPropertyValues()方法来获取PropertyValues为后续的填充属性做准备。

                  1
                  2
                  3
                  4
                  5
                  6
                  7
                  8
                  9
                  10
                  11
                  12
                  13
                  14
                  15
                  16
                  for (BeanPostProcessor bp : getBeanPostProcessors()) {
                  if (bp instanceof InstantiationAwareBeanPostProcessor) {
                  InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
                  PropertyValues pvsToUse = ibp.postProcessProperties(pvs, bw.getWrappedInstance(), beanName);
                  if (pvsToUse == null) {
                  if (filteredPds == null) {
                  filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
                  }
                  pvsToUse = ibp.postProcessPropertyValues(pvs, filteredPds, bw.getWrappedInstance(), beanName);
                  if (pvsToUse == null) {
                  return;
                  }
                  }
                  pvs = pvsToUse;
                  }
                  }
                • ③【赋值中】将后置处理器返回的PropertyValues(属性的值)给bean的属性赋值。 它的填充方式是通过访问属性set方法,所以需要你保证必须有属性对应的set方法才行。

                  1
                  2
                  3
                  if (pvs != null) {
                  applyPropertyValues(beanName, mbd, bw, pvs);
                  }
              • ⑤【bean初始化】调用AbstractAutowireCapableBeanFactory.initializeBean(beanName, exposedObject, mbd)方法。

                • ①执行Aware接口方法(BeanNameAware、BeanClassLoaderAware、BeanFactoryAware等),即调用invokeAwareMethods(beanName, bean)。

                  1
                  2
                  3
                  4
                  5
                  6
                  7
                  8
                  9
                  10
                  11
                  12
                  13
                  14
                  15
                  16
                  private void invokeAwareMethods(final String beanName, final Object bean) {
                  if (bean instanceof Aware) {
                  if (bean instanceof BeanNameAware) {
                  ((BeanNameAware) bean).setBeanName(beanName);
                  }
                  if (bean instanceof BeanClassLoaderAware) {
                  ClassLoader bcl = getBeanClassLoader();
                  if (bcl != null) {
                  ((BeanClassLoaderAware) bean).setBeanClassLoader(bcl);
                  }
                  }
                  if (bean instanceof BeanFactoryAware) {
                  ((BeanFactoryAware) bean).setBeanFactory(AbstractAutowireCapableBeanFactory.this);
                  }
                  }
                  }
                • ②执行后置处理器初始化之前的方法,即调用applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName),即调用此方法内的postProcessBeforeInitialization()方法。其中又包含一个特例,如果有同学了解过Bean初始化的几种手段的话,应该知道一个注解@PostConstruct,这种初始化的手段是在前置通知中完成的。实现类是CommonAnnotationBeanPostProcessor

                  1
                  2
                  3
                  4
                  5
                  6
                  7
                  8
                  9
                  10
                  11
                  12
                  13
                  14
                  @Override
                  public Object applyBeanPostProcessorsBeforeInitialization(Object existingBean, String beanName)
                  throws BeansException {

                  Object result = existingBean;
                  for (BeanPostProcessor processor : getBeanPostProcessors()) {
                  Object current = processor.postProcessBeforeInitialization(result, beanName);
                  if (current == null) {
                  return result;
                  }
                  result = current;
                  }
                  return result;
                  }
                • ③执行初始化方法,即调用invokeInitMethods(beanName, wrappedBean, mbd)。

                  • ①判断是否是InitializingBean接口的实现,执行接口规定的初始化。

                    1
                    2
                    3
                    4
                    5
                    6
                    7
                    8
                    9
                    10
                    11
                    12
                    13
                    14
                    15
                    16
                    17
                    18
                    19
                    20
                    boolean isInitializingBean = (bean instanceof InitializingBean);
                    if (isInitializingBean && (mbd == null || !mbd.isExternallyManagedInitMethod("afterPropertiesSet"))) {
                    if (logger.isTraceEnabled()) {
                    logger.trace("Invoking afterPropertiesSet() on bean with name '" + beanName + "'");
                    }
                    if (System.getSecurityManager() != null) {
                    try {
                    AccessController.doPrivileged((PrivilegedExceptionAction<Object>) () -> {
                    ((InitializingBean) bean).afterPropertiesSet();
                    return null;
                    }, getAccessControlContext());
                    }
                    catch (PrivilegedActionException pae) {
                    throw pae.getException();
                    }
                    }
                    else {
                    ((InitializingBean) bean).afterPropertiesSet();
                    }
                    }
                  • ②判断是否自定义初始化方法,执行自定义初始化方法。

                    1
                    2
                    3
                    4
                    5
                    6
                    7
                    8
                    if (mbd != null && bean.getClass() != NullBean.class) {
                    String initMethodName = mbd.getInitMethodName();
                    if (StringUtils.hasLength(initMethodName) &&
                    !(isInitializingBean && "afterPropertiesSet".equals(initMethodName)) &&
                    !mbd.isExternallyManagedInitMethod(initMethodName)) {
                    invokeCustomInitMethod(beanName, bean, mbd);
                    }
                    }
                • ④执行后置处理器初始化之后的方法,即调用applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName),即调用此方法内的postProcessAfterInitialization()方法。

                  1
                  2
                  3
                  4
                  5
                  6
                  7
                  8
                  9
                  10
                  11
                  12
                  13
                  14
                  @Override
                  public Object applyBeanPostProcessorsAfterInitialization(Object existingBean, String beanName)
                  throws BeansException {

                  Object result = existingBean;
                  for (BeanPostProcessor processor : getBeanPostProcessors()) {
                  Object current = processor.postProcessAfterInitialization(result, beanName);
                  if (current == null) {
                  return result;
                  }
                  result = current;
                  }
                  return result;
                  }
              • ⑥注册Bean的销毁方法,即调用registerDisposableBeanIfNecessary(beanName, bean, mbd)方法。 就是看下bean是否实现了DisposableBean接口,如果有,等bean销毁的时候调用其方法。

                1
                2
                3
                4
                5
                6
                7
                8
                9
                10
                11
                12
                13
                14
                15
                16
                17
                18
                19
                20
                21
                protected void registerDisposableBeanIfNecessary(String beanName, Object bean, RootBeanDefinition mbd) {
                AccessControlContext acc = (System.getSecurityManager() != null ? getAccessControlContext() : null);
                if (!mbd.isPrototype() && requiresDestruction(bean, mbd)) {
                if (mbd.isSingleton()) {
                // Register a DisposableBean implementation that performs all destruction
                // work for the given bean: DestructionAwareBeanPostProcessors,
                // DisposableBean interface, custom destroy method.
                registerDisposableBean(beanName,
                new DisposableBeanAdapter(bean, beanName, mbd, getBeanPostProcessors(), acc));
                }
                else {
                // A bean with a custom scope...
                Scope scope = this.scopes.get(mbd.getScope());
                if (scope == null) {
                throw new IllegalStateException("No Scope registered for scope name '" + mbd.getScope() + "'");
                }
                scope.registerDestructionCallback(beanName,
                new DisposableBeanAdapter(bean, beanName, mbd, getBeanPostProcessors(), acc));
                }
                }
                }
    • ④所有Bean都利用getBean创建完成以后,检查所有的Bean是否是实现了SmartInitializingSingleton接口的,如果是则执行afterSingletonsInstantiated()。

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      16
      // Trigger post-initialization callback for all applicable beans...
      for (String beanName : beanNames) {
      Object singletonInstance = getSingleton(beanName);
      if (singletonInstance instanceof SmartInitializingSingleton) {
      final SmartInitializingSingleton smartSingleton = (SmartInitializingSingleton) singletonInstance;
      if (System.getSecurityManager() != null) {
      AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
      smartSingleton.afterSingletonsInstantiated();
      return null;
      }, getAccessControlContext());
      }
      else {
      smartSingleton.afterSingletonsInstantiated();
      }
      }
      }
  • 打断点进入AbstractApplicationContext.finishRefresh()方法,完成BeanFactory的初始化创建工作,IOC容器就创建完成。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    protected void finishRefresh() {
    // Clear context-level resource caches (such as ASM metadata from scanning).
    //清除资源缓存
    clearResourceCaches();

    // Initialize lifecycle processor for this context.
    // // 1.为此上下文初始化生命周期处理器
    initLifecycleProcessor();

    // Propagate refresh to lifecycle processor first.
    // 2.首先将刷新完毕事件传播到生命周期处理器(触发isAutoStartup方法返回true的SmartLifecycle的start方法)
    getLifecycleProcessor().onRefresh();

    // Publish the final event.
    // 3.推送上下文刷新完毕事件到相应的监听器
    publishEvent(new ContextRefreshedEvent(this));

    // Participate in LiveBeansView MBean, if active.
    LiveBeansView.registerApplicationContext(this);
    }
    • ①清除资源缓存。

      1
      2
      3
      public void clearResourceCaches() {
      this.resourceCaches.clear();
      }
    • ②调用initLifecycleProcessor(),即初始化和生命周期有关的后置处理器,默认从容器中找是否有lifecycleProcessor的组件【LifecycleProcessor】,如果没有new DefaultLifecycleProcessor()加入到容器。

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      16
      17
      18
      19
      20
      21
      22
      23
      protected void initLifecycleProcessor() {
      ConfigurableListableBeanFactory beanFactory = getBeanFactory();
      // 1.判断BeanFactory是否已经存在生命周期处理器(固定使用beanName=lifecycleProcessor)
      if (beanFactory.containsLocalBean(LIFECYCLE_PROCESSOR_BEAN_NAME)) {
      this.lifecycleProcessor =
      beanFactory.getBean(LIFECYCLE_PROCESSOR_BEAN_NAME, LifecycleProcessor.class);
      if (logger.isTraceEnabled()) {
      logger.trace("Using LifecycleProcessor [" + this.lifecycleProcessor + "]");
      }
      }
      else {
      // 1.2 如果不存在,则使用DefaultLifecycleProcessor
      DefaultLifecycleProcessor defaultProcessor = new DefaultLifecycleProcessor();
      defaultProcessor.setBeanFactory(beanFactory);
      this.lifecycleProcessor = defaultProcessor;
      // 并将DefaultLifecycleProcessor作为默认的生命周期处理器,注册到BeanFactory中
      beanFactory.registerSingleton(LIFECYCLE_PROCESSOR_BEAN_NAME, this.lifecycleProcessor);
      if (logger.isTraceEnabled()) {
      logger.trace("No '" + LIFECYCLE_PROCESSOR_BEAN_NAME + "' bean, using " +
      "[" + this.lifecycleProcessor.getClass().getSimpleName() + "]");
      }
      }
      }
    • ③拿到前面定义的生命周期处理器(监听BeanFactory的生命周期),回调onRefresh(),将刷新完毕事件传播到生命周期处理器。即调用getLifecycleProcessor().onRefresh()。

      1
      2
      3
      4
      5
      @Override
      public void onRefresh() {
      startBeans(true);
      this.running = true;
      }
      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      16
      17
      18
      19
      20
      21
      22
      23
      24
      25
      26
      27
      28
      29
      30
      31
      32
      33
      34
      35
      36
      37
      private void startBeans(boolean autoStartupOnly) {
      // 1.获取所有的Lifecycle bean
      Map<String, Lifecycle> lifecycleBeans = getLifecycleBeans();

      // 将Lifecycle bean 按阶段分组,阶段通过实现Phased接口得到
      Map<Integer, LifecycleGroup> phases = new HashMap<>();
      // 2.遍历所有Lifecycle bean,按阶段值分组
      lifecycleBeans.forEach((beanName, bean) -> {
      // autoStartupOnly=true代表是ApplicationContext刷新时容器自动启动;autoStartupOnly=false代表是通过显示的调用启动
      // 3.当autoStartupOnly=false,也就是通过显示的调用启动,会触发全部的Lifecycle;
      // 当autoStartupOnly=true,也就是ApplicationContext刷新时容器自动启动,只会触发isAutoStartup方法返回true的SmartLifecycle

      if (!autoStartupOnly || (bean instanceof SmartLifecycle && ((SmartLifecycle) bean).isAutoStartup())) {
      // 3.1 获取bean的阶段值(如果没有实现Phased接口,则值为0)
      int phase = getPhase(bean);
      // 3.2 拿到存放该阶段值的LifecycleGroup
      LifecycleGroup group = phases.get(phase);
      if (group == null) {
      // 3.3 如果该阶段值的LifecycleGroup为null,则新建一个
      group = new LifecycleGroup(phase, this.timeoutPerShutdownPhase, lifecycleBeans, autoStartupOnly);
      phases.put(phase, group);
      }
      // 3.4 将bean添加到该LifecycleGroup
      group.add(beanName, bean);
      }
      });
      // 4.如果phases不为空
      if (!phases.isEmpty()) {
      List<Integer> keys = new ArrayList<>(phases.keySet());
      // 4.1 按阶段值进行排序
      Collections.sort(keys);
      // 4.2 按阶段值顺序,调用LifecycleGroup中的所有Lifecycle的start方法
      for (Integer key : keys) {
      phases.get(key).start();
      }
      }
      }
    • ④发布容器刷新完成事件,即推送上下文刷新完毕事件到相应的监听器。调用publishEvent(new ContextRefreshedEvent(this))。

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      16
      17
      18
      19
      20
      21
      22
      23
      24
      25
      26
      27
      28
      29
      30
      31
      32
      33
      34
      35
      36
      protected void publishEvent(Object event, @Nullable ResolvableType eventType) {
      Assert.notNull(event, "Event must not be null");

      // Decorate event as an ApplicationEvent if necessary
      // 1.如有必要,将事件装饰为ApplicationEvent
      ApplicationEvent applicationEvent;
      if (event instanceof ApplicationEvent) {
      applicationEvent = (ApplicationEvent) event;
      }
      else {
      applicationEvent = new PayloadApplicationEvent<>(this, event);
      if (eventType == null) {
      eventType = ((PayloadApplicationEvent<?>) applicationEvent).getResolvableType();
      }
      }

      // Multicast right now if possible - or lazily once the multicaster is initialized
      if (this.earlyApplicationEvents != null) {
      this.earlyApplicationEvents.add(applicationEvent);
      }
      else {
      // 2.使用事件广播器广播事件到相应的监听器
      getApplicationEventMulticaster().multicastEvent(applicationEvent, eventType);
      }

      // Publish event via parent context as well...
      // 3.同样的,通过parent发布事件.....
      if (this.parent != null) {
      if (this.parent instanceof AbstractApplicationContext) {
      ((AbstractApplicationContext) this.parent).publishEvent(event, eventType);
      }
      else {
      this.parent.publishEvent(event);
      }
      }
      }
  • 总结Spring容器启动流程:

    • Spring容器在启动的时候,先会保存所有注册进来的Bean的定义信息。
      • xml注册bean。
      • 注解注册Bean。
    • Spring容器会合适的时机创建这些Bean。
      • 用到这个bean的时候,利用getBean创建bean,创建好以后保存在容器中。
      • 统一创建剩下所有的bean:finishBeanFactoryInitialization()。
    • 执行后置处理器:BeanPostProcessor。
      • 每一个bean创建完成,都会使用各种后置处理器进行处理,来增强bean的功能。例如用AutowiredAnnotationBeanPostProcessor来处理自动注入;用AnnotationAwareAspectJAutoProxyCreator来处理AOP功能。