SpringBoot工程啟動順序與自定義監聽超詳細講解

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

@Component
public 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 Listeners
org.springframework.context.ApplicationListener=\
com.hsoft.demo.MyApplicationListener

推薦直接使用註解@ComponentaddListeners()方式,如果配置META-INF/spring.factories,因bootstrap配置分開加載所以監聽程序會被觸發兩次

3、創建ApplicationRunner和CommandLineRunner的實現類

隻需創建一個實現類型,並在實現類上面增加註解@Component即可

@Component
public class MyApplicationRunner implements ApplicationRunner {
    private final Logger logger = LoggerFactory.getLogger(getClass());
    @Override
    public void run(ApplicationArguments args) throws Exception {
        logger.info("MyApplicationRunner, {}",args.getOptionNames());
    }
}
@Component
public 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);
    }
}

到此這篇關於SpringBoot工程啟動順序與自定義監聽超詳細講解的文章就介紹到這瞭,更多相關SpringBoot工程啟動順序內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!

推薦閱讀: