(电脑系统boot内的启动顺序)

SpringBoot在2.4版本以后默认不加载bootstrap.yml配置项。 如果需要加载该配置项,需要引入依赖,通常Spring Cloud工程配合nacos这种配置中心或注册中心使用时,需要引入该依赖。

SpringBoot单体工程无需引入该依赖,所有配置放在application.yml中即可。

<!-- bootstrap 启动器 --><dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-bootstrap</artifactId></dependency>配置项

SpringBoot工程在启动时,会通过SpringFactoriesLoader检索META-INF/spring.factories文件,并加载其中的配置项。

常见的配置项有如下几种:

ApplicationContextInitializer:为在ApplicationContext执行refresh之前,调用ApplicationContextInitializer的initialize()方法,对ApplicationContext做进一步的设置和处理SpringApplicationRunListener:SpringBoot只提供一个实现类EventPublishingRunListener,在SpringBoot启动过程中,负责注册ApplicationListener监听器,在不同的时点发布不同的事件类型,如果有哪些ApplicationListener的实现类监听了这些事件,则可以接收并处理ApplicationListener:事件监听器,其作用可以理解为在SpringApplicationRunListener发布通知事件时,由ApplicationListener负责接收启动顺序说明

构造函数:初始化web容器,加载ApplicationContextInitializer的实现类并将其实例化,加载ApplicationListener的实现类并将其实例化

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容器类型,默认SERVLET,如果存在org.springframework.web.reactive.DispatcherHandler,则是REACTIVE this.webApplicationType = WebApplicationType.deduceFromClasspath(); this.bootstrapRegistryInitializers = new ArrayList<>( getSpringFactoriesInstances(BootstrapRegistryInitializer.class)); //找到*META-INF/spring.factories*中声明的所有ApplicationContextInitializer的实现类并将其实例化 setInitializers((Collection) getSpringFactoriesInstances(ApplicationContextInitializer.class)); //找到*META-INF/spring.factories*中声明的所有ApplicationListener的实现类并将其实例化 setListeners((Collection) getSpringFactoriesInstances(ApplicationListener.class)); //获得当前执行main方法的类对象 电脑 this.mainApplicationClass = deduceMainApplicationClass();}

启动方法

public ConfigurableApplicationContext run(String... args) { long startTime = System.nanoTime(); // 创建bootstrap上下文 DefaultBootstrapContext bootstrapContext = createBootstrapContext(); ConfigurableApplicationContext context = null; configureHeadlessProperty(); //通过*SpringFactoriesLoader*检索*META-INF/spring.factories*, //找到声明的所有SpringApplicationRunListener的实现类并将其实例化, //之后逐个调用其started()方法,广播SpringBoot要开始执行了。 SpringApplicationRunListeners listeners = getRunListeners(args); listeners.starting(bootstrapContext, this.mainApplicationClass); try { ApplicationArguments applicationArguments = new DefaultApplicationArguments(args); //创建并配置当前SpringBoot应用将要使用的Environment(包括配置要使用的PropertySource以及Profile), 电脑 //并遍历调用所有的SpringApplicationRunListener的environmentPrepared()方法,广播Environment准备完毕。 ConfigurableEnvironment environment = prepareEnvironment(listeners, bootstrapContext, applicationArguments); //决定是否打印Banner configureIgnoreBeanInfo(environment); Banner printedBanner = printBanner(environment); //根据webApplicationType的值来决定创建何种类型的ApplicationContext对象 //如果是SERVLET环境,则创建AnnotationConfigServletWebServerApplicationContext //如果是REACTIVE环境,则创建AnnotationConfigReactiveWebServerApplicationContext //否则创建AnnotationConfigApplicationContext context = createApplicationContext(); context.setApplicationStartup(this.applicationStartup); //为ApplicationContext加载environment,之后逐个执行ApplicationContextInitializer的initialize()方法来进一步封装ApplicationContext, //并调用所有的SpringApplicationRunListener的contextPrepared()方法,【EventPublishingRunListener只提供了一个空的contextPrepared()方法】, 电脑 //之后初始化IoC容器,并调用SpringApplicationRunListener的contextLoaded()方法,广播ApplicationContext的IoC加载完成, //这里就包括通过**@EnableAutoConfiguration**导入的各种自动配置类。 prepareContext(bootstrapContext, context, environment, listeners, applicationArguments, printedBanner); //初始化所有自动配置类,调用ApplicationContext的refresh()方法 refreshContext(context); //目前该方法为空 afterRefresh(context, applicationArguments); Duration timeTakenToStartup = Duration.ofNanos(System.nanoTime() - startTime); if (this.logStartupInfo) { new StartupInfoLogger(this.mainApplicationClass).logStarted(getApplicationLog(), timeTakenToStartup); } //调用所有的SpringApplicationRunListener的started()方法,广播SpringBoot已经完成了ApplicationContext初始化的全部过程。 listeners.started(context, timeTakenToStartup); //遍历所有注册的ApplicationRunner和CommandLineRunner,并执行其run()方法。 //该过程可以理解为是SpringBoot完成ApplicationContext初始化前的最后一步工作, //我们可以实现自己的ApplicationRunner或者CommandLineRunner,来对SpringBoot的启动过程进行扩展。 callRunners(context, applicationArguments); } catch (Throwable ex) { handleRunFailure(context, ex, listeners); throw new IllegalStateException(ex); } try { Duration timeTakenToReady = Duration.ofNanos(System.nanoTime() - startTime); listeners.ready(context, timeTakenToReady); } catch (Throwable ex) { handleRunFailure(context, ex, null); throw new IllegalStateException(ex); } return context;}扩展SpringApplication

我们的程序经常需要在启动过程中或启动完成后做一些额外的逻辑处理,那么可以通过以下三种方式处理:

1、创建ApplicationContextInitializer的实现类

1)创建实现类

public class MyApplicationContextInitializer implements ApplicationContextInitializer<ConfigurableApplicationContext> { private final Logger logger = LoggerFactory.getLogger(getClass()); @Override public void initialize(ConfigurableApplicationContext applicationContext) { logger.info("MyApplicationContextInitializer, {}", applicationContext.getApplicationName()); }}

2)配置META-INF/spring.factories

org.springframework.context.ApplicationContextInitializer=\ com.hsoft.demo.MyApplicationContextInitializer

3)或者修改启动方法,调用addInitializers添加

public static void main(String[] args) { SpringApplication springApplication = new SpringApplication(Application.class); springApplication.addInitializers(new MyApplicationContextInitializer()); springApplication.run(args);}2、创建ApplicationListener的实现类

ApplicationListener也有两种方式,首先创建实现类,然后修改启动方法,调用addListeners添加,或者直接添加注解@Component

@Componentpublic class MyApplicationListener implements ApplicationListener<ApplicationReadyEvent> { private final Logger logger = LoggerFactory.getLogger(getClass()); @Override public void onApplicationEvent(ApplicationReadyEvent event) { logger.info("MyApplicationListener,{}",event.toString()); }}

public static void main(String[] args) { SpringApplication springApplication = new SpringApplication(Application.class); springApplication.addListeners(new MyApplicationListener()); springApplication.run(args);}

也可以通过配置META-INF/spring.factories实现

# Application Listenersorg.springframework.context.ApplicationListener=\com.hsoft.demo.MyApplicationListener

推荐直接使用注解@Component或addListeners()方式,如果配置META-INF/spring.factories,因bootstrap配置分开加载所以监听程序会被触发两次

3、创建ApplicationRunner和CommandLineRunner的实现类

只需创建一个实现类型,并在实现类上面增加注解@Component即可

@Componentpublic class MyApplicationRunner implements ApplicationRunner { private final Logger logger = LoggerFactory.getLogger(getClass()); @Override public void run(ApplicationArguments args) throws Exception { logger.info("MyApplicationRunner, {}",args.getOptionNames()); }}

@Componentpublic class MyCommandLineRunner implements CommandLineRunner { private final Logger logger = LoggerFactory.getLogger(getClass()); @Override public void run(String... args) throws Exception { logger.info("MyCommandLineRunner, {}", args); }}生成war包在web容器(tomcat)中部署

如果SpringBoot工程要在Tomcat中部署,需要通过如下操作:

1、修改成war工程 2、嵌入式Tomcat依赖scope指定provided 3、编写SpringBootServletInitializer类子类,并重写configure方法

/** * web容器中进行部署 * */public class MyServletInitializer extends SpringBootServletInitializer { @Override protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { return application.sources(MyApplication.class); }}
电脑