目录
- 方法一:使用SpringCloud RestartEndpoint
- 方法二:重新创建ApplicationContext上下文
方法一:使用SpringCloud RestartEndpoint
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
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);
}
}
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();
}
}