Spring源码旅程

本文基于Spring 5.2.2.RELEASE进行Spring启动流程的梳理,只讨论大致流程的实现,其中一些重要的具体细节实现在后续文章中介绍。

Step0. Spring启动从下面自定义的程序开始,我们的旅程也从这里开始。

public class SpringApplication {
public static void main(String[] args){
        ApplicationContext context = new ClassPathXmlApplicationContext("application_context.xml");
        User user = (User) context.getBean("user");
        user.setName("雁阵惊寒");
        System.out.println(user);
    }
}

启动main方法,程序执行结果如下。

User{name='雁阵惊寒'}

程序中我们没有显式new一个新的User对象,而是通过一个xml配置文件application_context.xml进行配置,由Spring读取配置文件后创建的。这里相当于将本应该属于程序代码自己的对象初始化权限交给了Spring,所以称为控制反转(IoC,Inversion of Control),又因为是依赖于配置文件对对象进行初始化,也称为依赖注入(Dependency Injection)。两者本质上是相同的概念。

配置文件application_context.xml如下。



    

User类定义如下。

public class User {
    private String name;

    public String getName() {
        return name;
    }

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

    @Override
    public String toString() {
        return "User{" +
                "name='" + name + '\'' +
                '}';
    }
}

Step1. 创建ClassPathXmlApplicationContext上下文对象。

ApplicationContext context = new ClassPathXmlApplicationContext("application_context.xml");

进入到ClassPathXmlApplicationContext()构造函数中。setConfigLocations()函数将传入xml配置进行保存,代码中传入文件字符中的特殊意义符号,如${}也在这里进行处理转换。

public ClassPathXmlApplicationContext(String configLocation) throws BeansException {
    this(new String[] {configLocation}, true, null);
}
public ClassPathXmlApplicationContext(
    String[] configLocations, boolean refresh, @Nullable ApplicationContext parent)
      throws BeansException {
        super(parent);
        setConfigLocations(configLocations);
        if (refresh) {
          refresh();
        }
}

Step2. 进入refresh()函数,refresh()函数是Spring的核心函数,后起之秀Spring Boot也复用这里的逻辑,虽然具体实现类略有不同,但是思路大体一致。具体参看后续其他文章会详细讲解refresh()函数。这里只在源码中中文注释重要的函数功能,重要功能的界定原则是那些创建Bean的函数、为创建Bean初始化重要数据结构函数、进行AOP代理对象生成的函数。同时也标注Spring Boot相较于Spring的一些变动。

public void refresh() throws BeansException, IllegalStateException {
    synchronized (this.startupShutdownMonitor) {
      // Prepare this context for refreshing.
      prepareRefresh();

      // Tell the subclass to refresh the internal bean factory.
      //获取beanFactory
      //Spring会在这一步中解析xml文件转换为BeanDefinition结构
      //Spring Boot会将beanFactory创建提前到与容器创建时一起,
      //另外Spring Boot BeanDefinition的注册延后到了invokeBeanFactoryPostProcessors函数中完成
      ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();

      // Prepare the bean factory for use in this context.
      prepareBeanFactory(beanFactory);

      try {
        // Allows post-processing of the bean factory in context subclasses.
        postProcessBeanFactory(beanFactory);

        // Invoke factory processors registered as beans in the context.
        //Spring激活beanFactory处理器 
        //Spring Boot BeanDefinition的注册在这里完成
        invokeBeanFactoryPostProcessors(beanFactory);

        // Register bean processors that intercept bean creation.
        //Spring注册拦截Bean创建的Bean处理器
        registerBeanPostProcessors(beanFactory);

        // Initialize message source for this context.
        initMessageSource();

        // Initialize event multicaster for this context.
        initApplicationEventMulticaster();

        // Initialize other special beans in specific context subclasses.
        onRefresh();

        // Check for listener beans and register them.
        registerListeners();

        // Instantiate all remaining (non-lazy-init) singletons.
        //Spring初始化剩余的非惰性加载的单例
        //编写程序定义的Bean在这里创建
        finishBeanFactoryInitialization(beanFactory);

        // Last step: publish corresponding event.
        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();
      }
    }
}

Step3. 根据xml文件的配置,实际上走到这里示例代码中的User对象已经完成创建,我们具体看context.getBean("user")是如何获取对象的。

User user = (User) context.getBean("user");

Step4. 进入类AbstractApplicationContext中的getBean()函数。这里的getBeanFactory()函数走到AbstractRefreshableApplicationContext拿到beanFactory。beanFactory是在refresh()时进行的初始化。

@Override
public Object getBean(String name) throws BeansException {
    assertBeanFactoryActive();
    return getBeanFactory().getBean(name);
}

Step5. 类AbstractBeanFactory中的getBean()函数调用自身的doGetBean()函数。因为此时User对象已经创建(Step2中创建的),getSingleton()函数从容器缓存中获取Bean返回sharedInstance对象不为null,走if逻辑。

protected  T doGetBean(final String name, @Nullable final Class requiredType,
      @Nullable final Object[] args, boolean typeCheckOnly) throws BeansException {

    final String beanName = transformedBeanName(name);
    Object bean;

    // Eagerly check singleton cache for manually registered singletons.
    //getSingleton()函数从容器缓存中获取Bean
    Object sharedInstance = getSingleton(beanName);
    if (sharedInstance != null && args == null) {
      if (logger.isTraceEnabled()) {
        if (isSingletonCurrentlyInCreation(beanName)) {
          logger.trace("Returning eagerly cached instance of singleton bean '" + beanName +
              "' that is not fully initialized yet - a consequence of a circular reference");
        }
        else {
          logger.trace("Returning cached instance of singleton bean '" + beanName + "'");
        }
      }
      bean = getObjectForBeanInstance(sharedInstance, name, beanName, null);
    }

    else {
      //...因为此时User对象已经创建,不会再走else逻辑,暂时略去...
    }

    // Check if required type matches the type of the actual bean instance.
    //...略去暂时不用的代码...
    return (T) bean;
}

getSingleton()调用类AbstractBeanFactory的父类DefaultSingletonBeanRegistry中的函数getSingleton()。singletonObjects是一个map结构,存储着创建后的单例Bean。singletonObject对象不为null,直接返回。
下面这段getSingleton()函数代码展示了Spring解决循环依赖的三级缓存结构。

  • 一级缓存singletonObjects
  • 二级缓存earlySingletonObjects
  • 三级缓存singletonFactories

后续其他文章会有详细介绍Spring如何解决循环依赖问题。

@Nullable
protected Object getSingleton(String beanName, boolean allowEarlyReference) {
    //singletonObjects是一个map结构,存储着创建后的单例Bean。
    Object singletonObject = this.singletonObjects.get(beanName);
    if (singletonObject == null && isSingletonCurrentlyInCreation(beanName)) {
      synchronized (this.singletonObjects) {
        singletonObject = this.earlySingletonObjects.get(beanName);
        if (singletonObject == null && allowEarlyReference) {
          ObjectFactory singletonFactory = this.singletonFactories.get(beanName);
          if (singletonFactory != null) {
            singletonObject = singletonFactory.getObject();
            this.earlySingletonObjects.put(beanName, singletonObject);
            this.singletonFactories.remove(beanName);
          }
        }
      }
    }
    return singletonObject;
}
图片选自我的公众号

Step6. getObjectForBeanInstance()函数获取最终的对象。

bean = getObjectForBeanInstance(sharedInstance, name, beanName, null);
图片选自我的公众号

getObjectForBeanInstance()函数中,因为User对象本身并不是FactoryBean,直接返回传入的对象本身。

// Now we have the bean instance, which may be a normal bean or a FactoryBean.
// If it's a FactoryBean, we use it to create a bean instance, unless the
// caller actually wants a reference to the factory.
if (!(beanInstance instanceof FactoryBean)) {
      return beanInstance;
}

Step7. 到此为止,代码已经获取了Spring创建的User对象,与手动new的新对象一样。将对象创建移交给Spring处理,简化了代码编写复杂度,程序员不需要自己关注对象的初始化,也不需要编写复杂的代码逻辑对对象进行维护。Spring用容器维护对象,做到了随取随用。

对User对象的name字段进行赋值,然后打印。

User user = (User) context.getBean("user");
user.setName("雁阵惊寒");
System.out.println(user);

你可能感兴趣的:(Spring源码旅程)