SpringBoot自動重啟的兩種方法
更新時間:2023年12月08日 09:17:54 作者:Fisher3652
我們在項目開發(fā)階段,可能經常會修改代碼,修改完后就要重啟Spring Boot,本文主要介紹了SpringBoot自動重啟的兩種方法,具有一定的參考價值,感興趣的可以了解一下
方法一:使用SpringCloud RestartEndpoint
- 使用的jar
implementation 'org.springframework.boot:spring-boot-starter-actuator'
implementation 'org.springframework.cloud:spring-cloud-starter-config:3.0.7'
- 在application.properties添加配置
management.endpoint.restart.enabled=true spring.cloud.config.enabled=false
- 重啟方法的Controller
import javax.annotation.Resource;
import org.springframework.cloud.context.restart.RestartEndpoint;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/restart")
public class RestartController {
@Resource
private RestartEndpoint restartEndpoint;
@GetMapping("/restartApplication")
public void restartApplication() {
restartEndpoint.restart();
}
}
方法二:重新創(chuàng)建ApplicationContext上下文
- 啟動類
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
@SpringBootApplication
public class Application {
public static ConfigurableApplicationContext context;
public static void main(String[] args) {
context = SpringApplication.run(Application.class);
}
}
- 重啟方法的Controller
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.SpringApplication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import lombok.extern.slf4j.Slf4j;
@Slf4j
@RestController
@RequestMapping("/restart")
public class RestartController {
private static void restart() {
ApplicationArguments args = Application.context.getBean(ApplicationArguments.class);
Thread thread = new Thread(() -> {
log.info("springboot restart...");
Application.context.close();
Application.context = SpringApplication.run(Application.class, args.getSourceArgs());
});
// 設置為用戶線程,不是守護線程
thread.setDaemon(false);
thread.start();
}
}到此這篇關于SpringBoot自動重啟的兩種方法的文章就介紹到這了,更多相關SpringBoot自動重啟內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
使用EasyPoi實現百萬級數據導出的性能優(yōu)化方案
Easypoi 功能如同名字easy,主打的功能就是容易,讓一個沒見接觸過poi的人員 就可以方便的寫出Excel導出,Excel模板導出,Excel導入,本文給大家介紹了使用EasyPoi實現百萬級數據導出的性能優(yōu)化方案,需要的朋友可以參考下2025-08-08
SpringBoot2零基礎到精通之profile功能與自定義starter
SpringBoot是一種整合Spring技術棧的方式(或者說是框架),同時也是簡化Spring的一種快速開發(fā)的腳手架,本篇讓我們一起學習profile功能與自定義starter2022-03-03
SpringBoot Maven 項目 pom 中的 plugin&n
本文詳細介紹了Spring Boot Maven項目打包成jar文件時使用的spring-boot-maven-plugin插件,深入探討了插件的配置元素,結合實例代碼給大家介紹的非常詳細,感興趣的朋友一起看看吧2025-01-01

