通过HTTP重启Spring Boot应用程序
需求背景
有一个需求,要求在客户端动态修改Spring Boot配置文件中的属性,例如端口号、应用名称、数据库连接信息等,然后通过一个Http请求重启Spring Boot程序。这个需求类似于操作系统更新配置后需要进行重启系统才能生效的应用场景。
动态配置系统并更新生效是应用的一种通用性需求,实现的方式也有很多种。例如监听配置文件变化、使用配置中心等等。网络上也有很多类似的教程存在,但大多数都是在开发阶段,借助Spring Boot DevTools插件实现应用程序的重启,或者是使用spring-boot-starter-actuator和spring-cloud-starter-config来提供端点(Endpoint)的刷新。
第一种方式无法在生产环境中使用(不考虑),第二种方式需要引入Spring Cloud相关内容,这无疑是杀鸡用了宰牛刀。
接下来,我将尝试采用另外一种方式实现HTTP请求重启Spring Boot应用程序这个怪异的需求。
尝试思路
重启Spring Boot应用程序的关键步骤是对主类中SpringApplication.run(Application.class,args);方法返回值的处理。SpringApplication#run()方法将会返回一个ConfigurableApplicationContext类型对象,通过查看官方文档可以看到,ConfigurableApplicationContext接口类中定义了一个close()方法,可以用来关闭当前应用的上下文:
package org.springframework.context;
import java.io.Closeable;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.io.ProtocolResolver;
import org.springframework.lang.Nullable;
public interface ConfigurableApplicationContext extends ApplicationContext, Lifecycle, Closeable {
void close();
}
继续看官方源码,AbstractApplicationContext类中实现close()方法,下面是实现类中的方法摘要:
public void close() {
Object var1 = this.startupShutdownMonitor;
synchronized(this.startupShutdownMonitor) {
this.doClose();
if (this.shutdownHook != null) {
try {
Runtime.getRuntime().removeShutdownHook(this.shutdownHook);