在Spring Boot中,可以使用Spring Cloud Config来实现动态刷新配置。
下面是一种常见的方法:
- 首先,在Spring Boot项目的pom.xml文件中添加以下依赖:
org.springframework.cloud spring-cloud-starter-config
- 在application.properties文件中配置远程配置服务器的位置:
spring.cloud.config.uri=http://localhost:8888
- 创建一个新的配置类,用于获取配置信息:
import org.springframework.beans.factory.annotation.Value; import org.springframework.cloud.context.config.annotation.RefreshScope; import org.springframework.stereotype.Component; @Component @RefreshScope public class MyConfig { @Value("${my.config.property}") private String myConfigProperty; public String getMyConfigProperty() { return myConfigProperty; } }
- 在需要使用配置信息的地方注入MyConfig类,并使用其中的方法获取配置值:
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class MyController { @Autowired private MyConfig myConfig; @GetMapping("/myConfigProperty") public String getMyConfigProperty() { return myConfig.getMyConfigProperty(); } }
- 在更改配置信息时,可以通过POST请求
/actuator/refresh
来触发配置刷新:
curl -X POST http://localhost:8080/actuator/refresh
这样,配置信息就会从远程配置服务器更新到应用程序中。
注意:使用动态刷新配置时,还需要在启动类上添加@EnableConfigServer
注解。