详解Springboot应用启动以及关闭时完成某些操作
一:启动时完成数据加载等需求
实现ApplicationListener接口,官方文档截图:

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

应用监听器事件执行先后顺序如下:
- ApplicationStartingEvent
- ApplicationEnvironmentPreparedEvent
- ApplicationPreparedEvent
- ApplicationStartedEvent
- ApplicationReadyEvent
- ApplicationFailedEvent
实现CommandLineRunner和ApplicationRunner完成启动加载数据


二:关闭时完成某些操作
实现ApplicationListener<ContextClosedEvent>
实现DisposableBean接口

三、spring boot应用关闭操作(Linux/unix/ubuntu环境下进行)
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实现代码性能监控的方法详解
在开发过程中,偶尔还是需要分析代码的执行时间,Spring 框架提供了一个方便的工具类 StopWatch,本文将介绍 StopWatch 的基本用法,并通过示例演示如何在项目中使用 StopWatch 进行代码性能监控2023-12-12


最新评论