美文网首页
SpringApplication启动分析

SpringApplication启动分析

作者: louis_Huang | 来源:发表于2017-10-14 21:38 被阅读0次

Spring Boot是由Pivotal团队提供的全新框架,其设计目的是用来简化新Spring应用的初始搭建以及开发过程。
对绝大多数SpringBoot的用户来说,SpringBoot的感觉就是用起来很爽,但不知道怎么实现的。鄙人也属于其中一份子,现在决定读一遍源码,了解下原理。首先,来看一下SpringBoot是如何启动的。

1、创建一个SpringBoot的Demo

package com.louis.springboot.demo1;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class Demo1Application {
    public static void main(String[] args) {
       SpringApplication.run(Demo1Application.class, args);
    }
}

从代码中可以看出,SpringBoot的项目从通过SpringApplication的静态方法run来初始化项目。打开源码可以发现,SpringApplication类中有两个静态run方法,分别如下:

public static ConfigurableApplicationContext run(Object source, String... args) {
  return run(new Object[] { source }, args);
}

public static ConfigurableApplicationContext run(Object[] sources, String[] args) {
  return new SpringApplication(sources).run(args);
}

从方法的实现可以看出,run方法返回了一个新的SpringApplication的实例,并调用public ConfigurableApplicationContext run(String... args)方法。因此,启动的分析过程可从new SpringApplication(sources),以及run方法来分析;

2.SpringApplication的构造方法

SpringApplication的构造方法调用了initialize防范,两个方法的源码如下:

public SpringApplication(Object... sources) {
initialize(sources);
}

@SuppressWarnings({ "unchecked", "rawtypes" })
private void initialize(Object[] sources) {
  if (sources != null && sources.length > 0) {
    this.sources.addAll(Arrays.asList(sources));
  }
  this.webEnvironment = deduceWebEnvironment();
  setInitializers((Collection) getSpringFactoriesInstances(ApplicationContextInitializer.class));
  setListeners((Collection) getSpringFactoriesInstances(ApplicationListener.class));
  this.mainApplicationClass = deduceMainApplicationClass();
}

initialize方法主要完成的工作有:
1)判断是否是web程序(javax.servlet.Servlet和org.springframework.web.context.ConfigurableWebApplicationContext都必须在类加载器中存在),并设置到webEnvironment属性中;
2)从spring.factories文件中找出key为ApplicationContextInitializer的类并实例化后设置到SpringApplication的initializers属性中。这个过程也就是找出所有的应用程序初始化器;
3)从spring.factories文件中找出key为ApplicationListener的类并实例化后设置到SpringApplication的listeners属性中。这个过程就是找出所有的应用程序事件监听器;
4)找出main类,这里是Demo1Application类;

3.run方法分析

在分析run方法之前,先看下run方法的代码

     /**
     * Run the Spring application, creating and refreshing a new
     * {@link ApplicationContext}.
     * @param args the application arguments (usually passed from a Java main method)
     * @return a running {@link ApplicationContext}
     */
    public ConfigurableApplicationContext run(String... args) {
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();
        ConfigurableApplicationContext context = null;
        FailureAnalyzers analyzers = null;
        configureHeadlessProperty();
        SpringApplicationRunListeners listeners = getRunListeners(args);
        listeners.starting();
        try {
            ApplicationArguments applicationArguments = new DefaultApplicationArguments(
                    args);
            ConfigurableEnvironment environment = prepareEnvironment(listeners,
                    applicationArguments);
            Banner printedBanner = printBanner(environment);
            context = createApplicationContext();
            analyzers = new FailureAnalyzers(context);
            prepareContext(context, environment, listeners, applicationArguments,
                    printedBanner);
            refreshContext(context);
            afterRefresh(context, applicationArguments);
            listeners.finished(context, null);
            stopWatch.stop();
            if (this.logStartupInfo) {
                new StartupInfoLogger(this.mainApplicationClass)
                        .logStarted(getApplicationLog(), stopWatch);
            }
            return context;
        }
        catch (Throwable ex) {
            handleRunFailure(context, listeners, analyzers, ex);
            throw new IllegalStateException(ex);
        }
    }

1) 创建一个StopWatch,观察SpringApplication的执行;
2)获取所有的SpringApplicationRunListener并封装到SpringApplicationRunListeners中,用于监听run方法的执行。
3)创建Spring容器(ApplicationContext);
4)创建FailureAnalyzers对象,如果抛异常,则将analyzers传入失败处理流程;
5)处理容器准备(设置环境,处理listenrs,处理参数,设置banners)、刷新的事务;

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
        context.getBeanFactory().registerSingleton("springApplicationArguments",
                applicationArguments);
        if (printedBanner != null) {
            context.getBeanFactory().registerSingleton("springBootBanner", printedBanner);
        }

        // Load the sources
        Set<Object> sources = getSources();
        Assert.notEmpty(sources, "Sources must not be empty");
        load(context, sources.toArray(new Object[sources.size()]));
        listeners.contextLoaded(context);
    }

    private void refreshContext(ConfigurableApplicationContext context) {
        refresh(context);
        if (this.registerShutdownHook) {
            try {
                context.registerShutdownHook();
            }
            catch (AccessControlException ex) {
                // Not allowed in some environments.
            }
        }
    }
protected void afterRefresh(ConfigurableApplicationContext context,
            ApplicationArguments args) {
        callRunners(context, args);
    }

相关文章

网友评论

      本文标题:SpringApplication启动分析

      本文链接:https://www.haomeiwen.com/subject/gbifuxtx.html