在本教程中,我们将学习如何在Spring Boot中重新加载应用程序属性。在这里解释最简单的选择:使用@ConfigurationProperties刷新bean。
对于Reloading属性,Spring Cloud引入了@RefreshScope注解,可用于刷新bean。
Spring Actuator提供了各种不同的端点用于健康状况指标,Spring Cloud会添加额外的端点/ refresh以重新加载所有属性。
依赖
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-actuator</artifactId> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter</artifactId> </dependency>
|
加入下面熟悉到application属性文件:
management.endpoints.web.exposure.include=refresh
// Db Properties, Values to be store in a Map db.dbProps.awsEndPoint=localhost:8080/aws/ db.dbProps.azureEndPoint=localhost:8080/azure/
|
现在创建一个配置类,并使用@RefreshScope注解它:
@Component @ConfigurationProperties(prefix = "db") @RefreshScope public class DbProperties {
// This is for storing application properties in a Map public Map<String, String> dbProps;
public Map<String, String> getDbProps() { return dbProps; }
public void setDbProps(Map<String, String> dbProps) { this.dbProps = dbProps; }
// Get property value using key public String getDbPropData(String key) { return dbProps.get(key); } }
|
现在,当您更改应用程序属性中的数据时。我们需要使用以下URL进行POST REST调用:
http://localhost:8080/actuator/refresh
|