配置版本信息
spring boot 2.1.0 RELEASE
Spring Cloud Finchley.SR2
build Maven
为了实现动态刷新配置文件我们需要spring-boot-starter-actuator
提供刷新接口,spring-cloud-starter-config
提供动态监测注解。
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.0.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>Finchley.SR2</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-config</artifactId>
</dependency>
</dependencies>
配置使用
我们以一个简单的配置为例。
首先在application.yml
中增加了一个配置项如下
access-contrl:
enable: false
whiteList:
- "172.22.25.96"
- "127.0.0.1"
然后创建一个与这个结构对应的POJO对象
注意:必须提供对象属性的
Getter
和Setter
方法,否则Spring无法把配置文件的值注入。
import java.util.HashSet;
import java.util.Set;
public class IpWhiteListConfig {
private boolean enable;
private Set<String> whiteList;
public IpWhiteListConfig() {
this.whiteList = new HashSet<>();
}
public Set<String> getWhiteList() {
return whiteList;
}
public void setWhiteList(Set<String> whiteList) {
this.whiteList = whiteList;
}
public boolean isEnable() {
return enable;
}
public void setEnable(boolean enable) {
this.enable = enable;
}
}
首先使用@ConfigurationProperties
注解标识这是一个配置项的Bean,在@ConfigurationProperties
可以为这个配置Bean提供前缀,用于与配置文件上中内容对应上(此例子中对应prefix
,应该是access-contrl
)。然后加上@RefreshScope
让Spring动态刷新该Bean。最后为了使用这个配置Bean我们为他设置@Component
注解以便在需要的地方注入该配置。
@ConfigurationProperties(prefix = "access-contrl")
@RefreshScope
@Component
public class IpWhiteListConfig {
....
}
完成上述配置创建后,为了开启/actuator/refresh
接口的,还需要在application.yml
中加入下面配置项,表明需要开启该接口。
management:
endpoints:
web:
exposure:
include: refresh
关于
Spring Boot Actuator
的更多配置请参考 Spring Boot Actuator: 53. Endpoints
在需要刷新配置项的使用,请使用 POST
的方法请求项目的/actuator/refresh
,就能够动态刷新配置项。
测试
我们创建一个最简单的控制器
@RestController
public class TestController {
@Autowired
private IpWhiteListConfig ipWhiteListConfig;
@GetMapping("/access")
public Object access() {
System.out.println(ipWhiteListConfig);
return ipWhiteListConfig.getWhiteList();
}
}
然后将项目打通过mvn package
打为Jar包,接下来将项目中的application.yml
复制一份并放到与该jar包同一级目录中。启动
java jar demo.jar
访问http://localhost:8080/access
接口返还如下数据
[
"172.22.25.96",
"127.0.0.1"
]
然后我们在与jar包同级目录中的application.yml
的whiteList
加入下面0.0.0.0
,
access-contrl:
enable: false
whiteList:
- "172.22.25.96"
- "127.0.0.1"
- "0.0.0.0"
使用 POST
的方法请求项目的http://localhost:8080/actuator/refresh
。
再次访问http://localhost:8080/access
接口
[
"0.0.0.0",
"172.22.25.96",
"127.0.0.1"
]
可以看到配置项已经被刷新