搬砖小弟
SpringBoot - 启动原理
2019-07-20 / 3 min read

SpringBoot应用启动类一般如下:

@SpringBootApplication
public class SampleRabbitmqApplication {

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

}

@SpringBootApplication

@SpringBootApplication这个组合注解包含了三个注解 :

  • @SpringBootConfiguration
  • @EnableAutoConfiguration
  • @ComponentScan

@SpringBootConfiguration实际上应用@Configuration, 任何注解了Configuration了java类都是一个JavaConfig配置类。
@ComponentScan的功能是自动扫描并加载符合条件的组件(如@Component和@Repository),最终将这些bean加载IoC容器中。
@EnableAutoConfiguration借助@Import收集和注册特定场景相关的bean定义。

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@AutoConfigurationPackage
@Import(AutoConfigurationImportSelector.class)
public @interface EnableAutoConfiguration {

	String ENABLED_OVERRIDE_PROPERTY = "spring.boot.enableautoconfiguration";

	/**
	 * Exclude specific auto-configuration classes such that they will never be applied.
	 * @return the classes to exclude
	 */
	Class<?>[] exclude() default {};

	/**
	 * Exclude specific auto-configuration class names such that they will never be
	 * applied.
	 * @return the class names to exclude
	 * @since 1.3.0
	 */
	String[] excludeName() default {};

}

@Import(AutoConfigurationImportSelector.class)中借助AutoConfigurationImportSelector可以帮助SpringBoot应用将所有符合@Configuration配置都加载到当SpringBoot创建IoC容器中。AutoConfigurationImportSelector使用SpringFactoriesLoader从META-INF/spring.factories加载配置。

SpringApplication.run

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;
	}
  1. 创建SpringApplicationRunListeners, 获取SpringFactoriesInstances实例
  2. 准备环境变量
  3. 是否打印banner
  4. 创建ApplicationContext,servelt环境创建AnnotationConfigServletWebServerApplicationContext, reactive环境创建AnnotationConfigReactiveWebServerApplicationContext, 否则创建AnnotationConfigApplicationContext
  5. prepareContext, 主要是ApplicationContextInitializer的初始化
  6. refreshContext 调用ApplicationContext的refresh()方法
  7. afterRefresh, 空方法