詳解Springboot應用啟動以及關閉時完成某些操作
一:啟動時完成數據加載等需求
實現ApplicationListener接口,官方文檔截圖:

ApplicationListener接口的泛型類可以使用ApplicationStartedEvent和ApplicationReadyEvent

應用監(jiān)聽器事件執(zhí)行先后順序如下:
- ApplicationStartingEvent
- ApplicationEnvironmentPreparedEvent
- ApplicationPreparedEvent
- ApplicationStartedEvent
- ApplicationReadyEvent
- ApplicationFailedEvent
實現CommandLineRunner和ApplicationRunner完成啟動加載數據


二:關閉時完成某些操作
實現ApplicationListener<ContextClosedEvent>
實現DisposableBean接口

三、spring boot應用關閉操作(Linux/unix/ubuntu環(huán)境下進行)
A、非安全驗證
1、項目pom.xml添加如下依賴包:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-actuator</artifactId> </dependency>
2、application.properties文件添加如下內容:
#啟用shutdownendpoints.shutdown.enabled=true#禁用密碼驗證endpoints.shutdown.sensitive=false
3、關閉命令:
curl -X POST host:port/shutdown
B、安全驗證
1、pom.xml添加如下依賴包:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency>
2、application.properties文件添加以下內容:
#開啟shutdown的安全驗證endpoints.shutdown.sensitive=true #驗證用戶名security.user.name=admin #驗證密碼security.user.password=admin #角色management.security.role=SUPERUSER # 指定端口management.port=8081 # 指定地址management.address=127.0.0.1
3、關閉命令:
curl -u admin:admin -X POST http://127.0.0.1:8081/manage/shutdown
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
用Java集合中的Collections.sort方法如何對list排序(兩種方法)
本文通過兩種方法給大家介紹java集合中的Collections.sort方法對list排序,第一種方式是list中的對象實現Comparable接口,第二種方法是根據Collections.sort重載方法實現,對collections.sort方法感興趣的朋友一起學習吧2015-10-10
源碼分析Java中ThreadPoolExecutor的底層原理
這篇文章主要帶大家從源碼分析一下Java中ThreadPoolExecutor的底層原理,文中的示例代碼講解詳細,具有一定的學習價值,需要的可以參考一下2023-05-05
Spring整合SpringMVC + Mybatis基礎框架的配置文件詳解
這篇文章主要介紹了Spring整合SpringMVC + Mybatis基礎框架的配置文件,本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2021-02-02
使用Spring的StopWatch實現代碼性能監(jiān)控的方法詳解
在開發(fā)過程中,偶爾還是需要分析代碼的執(zhí)行時間,Spring 框架提供了一個方便的工具類 StopWatch,本文將介紹 StopWatch 的基本用法,并通過示例演示如何在項目中使用 StopWatch 進行代碼性能監(jiān)控2023-12-12

