SpringBoot_启动配置原理(2.2.5 version)

启动配置原理

几个重要的事件回调机制

配置在META-INF/spring.factories

ApplicationContextInitializer

SpringApplicationRunListener

只需要放在ioc容器中

ApplicationRunner

CommandLineRunner

启动流程:

1. 创建SpringApplication对象

/**
 * Create a new {@link SpringApplication} instance. The application context will load
 * beans from the specified primary sources (see {@link SpringApplication class-level}
 * documentation for details. The instance can be customized before calling
 * {@link #run(String...)}.
 * @param resourceLoader the resource loader to use
 * @param primarySources the primary bean sources
 * @see #run(Class, String[])
 * @see #setSources(Set)
 */
@SuppressWarnings({ "unchecked", "rawtypes" })
public SpringApplication(ResourceLoader resourceLoader, Class<?>... primarySources) {
	this.resourceLoader = resourceLoader;
	//保存主配置类
	Assert.notNull(primarySources, "PrimarySources must not be null");
	this.primarySources = new LinkedHashSet<>(Arrays.asList(primarySources));
	//判断当前web应用类型,有以下三种类型:
	/**
	 * The application should not run as a web application and should not start an
	 * embedded web server.
	 */
	//NONE,

	/**
	 * The application should run as a servlet-based web application and should start an
	 * embedded servlet web server.
	 */
	//SERVLET,

	/**
	 * The application should run as a reactive web application and should start an
	 * embedded reactive web server.
	 */
	//REACTIVE;
	this.webApplicationType = WebApplicationType.deduceFromClasspath();
	//从类路径下找到META-INF/spring.factories配置的所有ApplicationContextInitializer;然后保存起来
	setInitializers((Collection) getSpringFactoriesInstances(ApplicationContextInitializer.class));
	////从类路径下找到ETA-INF/spring.factories配置的所有ApplicationListener
	setListeners((Collection) getSpringFactoriesInstances(ApplicationListener.class));
	//从多个配置类中找到有main方法的主配置类
	this.mainApplicationClass = deduceMainApplicationClass();
}

在这里插入图片描述

在这里插入图片描述

2. 运行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;
	//异常记录
	Collection<SpringBootExceptionReporter> exceptionReporters = new ArrayList<>();
	//awt相关
	configureHeadlessProperty();
	//获取SpringApplicationRunListeners;从类路径下META-INF/spring.factories
	SpringApplicationRunListeners listeners = getRunListeners(args);
	//回调所有的获取SpringApplicationRunListener.starting()方法
	listeners.starting();
	try {
		//封装命令行参数
		ApplicationArguments applicationArguments = new DefaultApplicationArguments(args);
		//准备环境,创建和配置环境,创建环境完成后回调SpringApplicationRunListener.environmentPrepared();表示环境准备完成
		ConfigurableEnvironment environment = prepareEnvironment(listeners, applicationArguments);
		//spring.beaninfo.ignore设置忽略的bean
		configureIgnoreBeanInfo(environment);
		//打印banner
		Banner printedBanner = printBanner(environment);
		//创建ApplicationContext;决定创建不同类型的ioc
		context = createApplicationContext();
		//异常处理报告
		exceptionReporters = getSpringFactoriesInstances(SpringBootExceptionReporter.class,
				new Class[] { ConfigurableApplicationContext.class }, context);
		//准备上下文环境;将environment保存到ioc中;而且applyInitializers();
       	//applyInitializers():回调之前保存的所有的ApplicationContextInitializer的initialize方法
       	//回调所有的SpringApplicationRunListener的contextPrepared()
        //prepareContext运行完成以后回调所有的SpringApplicationRunListener的contextLoaded()
		prepareContext(context, environment, listeners, applicationArguments, printedBanner);
		//刷新容器;ioc容器初始化(如果是web应用还会创建嵌入式的Tomcat)
       	//扫描,创建,加载所有组件的地方;(配置类,组件,自动配置)
		refreshContext(context);
		//空方法,啥也没干
		afterRefresh(context, applicationArguments);
		//停止计时
		stopWatch.stop();
		//记录启动信息
		if (this.logStartupInfo) {
			new StartupInfoLogger(this.mainApplicationClass).logStarted(getApplicationLog(), stopWatch);
		}
		//所有的SpringApplicationRunListener回调started方法
		listeners.started(context);
		//从ioc容器中获取所有的ApplicationRunner和CommandLineRunner进行回调
       	//ApplicationRunner先回调,CommandLineRunner再回调
		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);
	}
	//整个SpringBoot应用启动完成以后返回启动的ioc容器
	return context;
}

3. 事件监听机制

配置在META-INF/spring.factories

ApplicationContextInitializer

public class HelloApplicationContextInitializer implements ApplicationContextInitializer<ConfigurableApplicationContext> {
    @Override
    public void initialize(ConfigurableApplicationContext applicationContext) {
        System.out.println("ApplicationContextInitializer...initialize..."+applicationContext);
    }
}

SpringApplicationRunListener

public class HelloSpringApplicationRunListener implements SpringApplicationRunListener {

    //必须的有参构造器
    public HelloSpringApplicationRunListener(SpringApplication application, String[] args){

    }
    @Override
    public void starting() {
        System.out.println("SpringApplicationRunListener...starting...");
    }

    @Override
    public void environmentPrepared(ConfigurableEnvironment environment) {
        Object o = environment.getSystemProperties().get("os.name");
        System.out.println("SpringApplicationRunListener...environmentPrepared.."+o);
    }

    @Override
    public void contextPrepared(ConfigurableApplicationContext context) {
        System.out.println("SpringApplicationRunListener...contextPrepared...");
    }

    @Override
    public void contextLoaded(ConfigurableApplicationContext context) {
        System.out.println("SpringApplicationRunListener...contextLoaded...");
    }

    @Override
    public void started(ConfigurableApplicationContext context, Throwable exception) {
        System.out.println("SpringApplicationRunListener...started...");
    }
}

配置(META-INF/spring.factories)

org.springframework.context.ApplicationContextInitializer=\
com.test.springboot.listener.HelloApplicationContextInitializer

org.springframework.boot.SpringApplicationRunListener=\
com.test.springboot.listener.HelloSpringApplicationRunListener

只需要放在ioc容器中

ApplicationRunner

@Component
public class HelloApplicationRunner implements ApplicationRunner {
    @Override
    public void run(ApplicationArguments args) throws Exception {
        System.out.println("ApplicationRunner...run....");
    }
}

CommandLineRunner

@Component
public class HelloCommandLineRunner implements CommandLineRunner {
    @Override
    public void run(String... args) throws Exception {
        System.out.println("CommandLineRunner...run..."+ Arrays.asList(args));
    }
}

在这里插入图片描述

发布了417 篇原创文章 · 获赞 45 · 访问量 6万+

猜你喜欢

转载自blog.csdn.net/Chill_Lyn/article/details/104781218