SpringBoot自动重启的两种方法
作者:Fisher3652
我们在项目开发阶段,可能经常会修改代码,修改完后就要重启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(); } }
方法二:重新创建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自动重启内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!