SpringBoot 源码解析 —— SpringApplication 源码分析

点击上方 "Java指南者"关注, 星标或置顶一起成长

免费送 1024GB 精品学习资源 

正常的 SpringBoot 应用程序


一个正常的 SpringBoot 项目的启动类中常见代码如下:

@SpringBootApplication
public class SpringbotApplication {
 public static void main(String[] args) {
  SpringApplication.run(SpringbotApplication.class, args);
 }
}

上面的代码也就两个比较引人注意的地方:

  • @SpringBootApplication

  • SpringApplication.run()


对于 SpringBootApplication 注解不在本文讲解,本文主要讲解一下 SpringApplication 类的 run 方法,这个 run 方法是一个静态的方法,其实内部是进行构造 SpringBootApplication 对象,然后调用了 run 方法。


所以其实你像下面这样写代码也是可以的:

@SpringBootApplication
public class SpringbotApplication {  
 public static void main(String[] args) {
  SpringApplication app = new SpringApplication(SpringbotApplication.class);
   // 自定义应用程序的配置
   //app.setXxx()
   app.run(args)
 }
}

SpringApplication 构造器




该构造方法中会创建一个 SpringApplication 实例,应用上下文会根据指定的资源加载 beans,在调用 run 方法之前可以自定义该实例。

  • resourceLoader:资源加载器

  • primarySources:启动类

  • webApplicationType:应用类型,有 _NONE、SERVLET、REACTIVE _三种类型,通过 deduceFromClasspath 函数进行判断

//通过反射判断
static WebApplicationType deduceFromClasspath() {
    if (ClassUtils.isPresent(WEBFLUX_INDICATOR_CLASS, null) && !ClassUtils.isPresent(WEBMVC_INDICATOR_CLASS, null)
        && !ClassUtils.isPresent(JERSEY_INDICATOR_CLASS, null)) {
        return WebApplicationType.REACTIVE;
    }
    for (String className : SERVLET_INDICATOR_CLASSES) {
        if (!ClassUtils.isPresent(className, null)) {
            return WebApplicationType.NONE;
        }
    }
    return WebApplicationType.SERVLET;
}
  • ApplicationContextInitializer:初始化 classpath 下的所有的可用的 ApplicationContextInitializer

setInitializers((Collection) getSpringFactoriesInstances(ApplicationContextInitializer.class));

private <T> Collection<T> getSpringFactoriesInstances(Class<T> type) {
    return getSpringFactoriesInstances(type, new Class<?>[] {});
}

private <T> Collection<T> getSpringFactoriesInstances(Class<T> type, Class<?>[] parameterTypes, Object... args) {
    ClassLoader classLoader = getClassLoader();
    // Use names and ensure unique to protect against duplicates
    Set<String> names = new LinkedHashSet<>(SpringFactoriesLoader.loadFactoryNames(type, classLoader));
    List<T> instances = createSpringFactoriesInstances(type, parameterTypes, classLoader, args, names);
    AnnotationAwareOrderComparator.sort(instances);
    return instances;
}

在 getSpringFactoriesInstances 方法中会通过 SpringFactoriesLoader.loadFactoryNames() 加载所有的 ApplicationContextInitializer,该类方法是 spring-core 里面的代码了,它会先根据类加载器从 cache 中找是否加载过,否则会通过类加载器去加载 META-INF/spring.factories 文件中的 ApplicationContextInitializer。


来看下 META-INF/spring.factories 文件中的内容:



应该就是去加载找上图标记中的 Application Context Initializers 。

找到的结果如下图所示:


找到这些 ApplicationContextInitializer 后需要做的是创建 spring 工厂实例:


  • ApplicationListener:初始化 classpath 下的所有的可用的 ApplicationListener


这个和上面的初始化 classpath 下的所有的可用的 ApplicationContextInitializer 是一样的,也是通过一样的方式去加载 META-INF/spring.factories 文件中所有的 Application Listeners,文件内容如下:



找到的结果如下图所示:


  • mainApplicationClass:找到带有 main 方法的主类名称

run 方法


run 方法上面的注释的意思大概是说:启动 Spring 应用程序,创建和更新一个 ApplicationContext 。



看看方法中的具体代码:

public ConfigurableApplicationContext run(String... args) {
    StopWatch stopWatch = new StopWatch();
    stopWatch.start();
    ConfigurableApplicationContext context = null;
    Collection<SpringBootExceptionReporter> exceptionReporters = new ArrayList<>();
    configureHeadlessProperty();
    SpringApplicationRunListeners listeners = getRunListeners(args);
    listeners.starting();
    try {
        ApplicationArguments applicationArguments = new DefaultApplicationArguments(args);
        ConfigurableEnvironment environment = prepareEnvironment(listeners, applicationArguments);
        configureIgnoreBeanInfo(environment);
        Banner printedBanner = printBanner(environment);
        context = createApplicationContext();
        exceptionReporters = getSpringFactoriesInstances(SpringBootExceptionReporter.class,
                                                         new Class[] { ConfigurableApplicationContext.class }, context);
        prepareContext(context, environment, listeners, applicationArguments, printedBanner);
        refreshContext(context);
        afterRefresh(context, applicationArguments);
        stopWatch.stop();
        if (this.logStartupInfo) {
            new StartupInfoLogger(this.mainApplicationClass).logStarted(getApplicationLog(), stopWatch);
        }
        listeners.started(context);
        callRunners(context, applicationArguments);
    }
    catch (Throwable ex) {
        handleRunFailure(context, ex, exceptionReporters, listeners);
        throw new IllegalStateException(ex);
    }

    try {
        listeners.running(context);
    }
    catch (Throwable ex) {
        handleRunFailure(context, ex, exceptionReporters, null);
        throw new IllegalStateException(ex);
    }
    return context;
}


我们挑该方法中比较重要的进行讲解:

  • getRunListeners:该方法利用和上面一样的加载方法会去读取 classpath 下的 SpringApplicationRunListeners



META-INF/spring.factories 文件中的 SpringApplicationRunListener 有:



该 listener 只负责 run 方法的监听



它的状态有下面几种:


  • prepareEnvironment:根据 listeners 和 applicationArguments 配置 SpringBoot 应用的环境



  • configureIgnoreBeanInfo:根据环境信息配置要忽略的 bean 信息



  • printBanner:打印 spring boot 的标志,可以自定义

  • createApplicationContext:根据应用类型来确定该 Spring Boot 项目应该创建什么类型的 ApplicationContext ,默认情况下,如果没有明确设置的应用程序上下文或应用程序上下文类,该方法会在返回合适的默认值




然后又用到了反射,可以看到目前为止,代码也是大量使用的 Java 中的反射。

  • get SpringBootExceptionReporter:也是通过 getSpringFactoriesInstances 方法获取到 classpath 下的 SpringBootExceptionReporter


从到目前的代码可以发现,在 SpringBoot 里面大量使用了这种 SPI 加载机制。

  • prepareContext:完成整个容器的创建与启动以及 bean 的注入功能

private void prepareContext(ConfigurableApplicationContext context, ConfigurableEnvironment environment,
                            SpringApplicationRunListeners listeners, ApplicationArguments applicationArguments, Banner printedBanner) {
    context.setEnvironment(environment);
    postProcessApplicationContext(context);
    applyInitializers(context);
    listeners.contextPrepared(context);
    if (this.logStartupInfo) {
        logStartupInfo(context.getParent() == null);
        logStartupProfileInfo(context);
    }
    // Add boot specific singleton beans
    ConfigurableListableBeanFactory beanFactory = context.getBeanFactory();
    beanFactory.registerSingleton("springApplicationArguments", applicationArguments);
    if (printedBanner != null) {
        beanFactory.registerSingleton("springBootBanner", printedBanner);
    }
    if (beanFactory instanceof DefaultListableBeanFactory) {
        ((DefaultListableBeanFactory) beanFactory)
        .setAllowBeanDefinitionOverriding(this.allowBeanDefinitionOverriding);
    }
    if (this.lazyInitialization) {
        context.addBeanFactoryPostProcessor(new LazyInitializationBeanFactoryPostProcessor());
    }
    // Load the sources
    Set<Object> sources = getAllSources();
    Assert.notEmpty(sources, "Sources must not be empty");
    load(context, sources.toArray(new Object[0]));
    listeners.contextLoaded(context);
}

postProcessApplicationContext 该方法对 context 进行了预设置,设置了 ResourceLoader、ClassLoader 和 ConversionService,并向 bean 工厂中添加了一个 beanNameGenerator 。

applyInitializers 方法将刚才获取到的所有 ApplicationContextInitializer 进行初始化。

listeners.contextPrepared(context) 对所有的 SpringApplicationRunListeners 进行创建和准备应用上下文,在加载资源之前调用。

load(context, sources.toArray(new Object[0])) 主要是加载各种 beans 到 ApplicationContext 对象中。

contextLoaded 方法会将所有的应用上下文进行加载。

  • refreshContext:更新应用上下文,最后是调用下面该方法


  • afterRefresh(): 在上下文刷新后调用该方法,其内部没有做任何操作

  • listeners.started(context): 应用上下文更新了,应用也开启了,但是 _CommandLineRunner _和 _ApplicationRunner _还没有调用

  • callRunners:ApplicationRunner 和 CommandLineRunner 进行回调



  • listeners.running(context):接着就是改变状态为 running 了


整个 run 方法中的 SpringApplicationRunListeners 的状态变更顺序如下:

可以发现 SpringApplicationRunListeners 这个类已经在 run 方法里面有经过 6 次的状态变更,那么它所有的状态有哪些呢?我们来一起瞧瞧:


还有一种就是当出现异常的时候,就会 failed,这个是在 catch 里面会做状态变更的。

关注我

关注我,Java 学习不迷路!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值