Java Spring配置服务器在运行时添加属性
我想在spring config server的运行时添加一些属性,它应该对所有带有Java Spring配置服务器在运行时添加属性,java,spring,spring-boot,spring-cloud-config,Java,Spring,Spring Boot,Spring Cloud Config,我想在spring config server的运行时添加一些属性,它应该对所有带有@Value注释的客户端应用程序都可用 我不会预先定义这个属性,因为我将在SpringConfigServer中计算该值并添加到环境中 请您帮助我了解实现这一点的最佳方法。Spring云配置包含一个名为“”的功能,它允许刷新正在运行的应用程序的属性和bean 如果您阅读了SpringCloud配置,它看起来只能从git存储库加载属性,但事实并非如此 您可以使用RefreshScope从本地文件重新加载属性,而无需
@Value
注释的客户端应用程序都可用
我不会预先定义这个属性,因为我将在SpringConfigServer中计算该值并添加到环境中
请您帮助我了解实现这一点的最佳方法。Spring云配置包含一个名为“”的功能,它允许刷新正在运行的应用程序的属性和bean 如果您阅读了SpringCloud配置,它看起来只能从git存储库加载属性,但事实并非如此 您可以使用RefreshScope从本地文件重新加载属性,而无需连接到外部git存储库或HTTP请求 使用以下内容创建文件
bootstrap.properties
:
# false: spring cloud config will not try to connect to a git repository
spring.cloud.config.enabled=false
# let the location point to the file with the reloadable properties
reloadable-properties.location=file:/config/defaults/reloadable.properties
在上面定义的位置创建一个文件reloadable.properties
。
您可以将其保留为空,或添加一些属性。在此文件中,您可以稍后在运行时更改或添加属性
将依赖项添加到
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-config</artifactId>
</dependency>
创建一个类
public class ReloadablePropertySourceLocator implements PropertySourceLocator
{
private final String location;
public ReloadablePropertySourceLocator(
@Value("${reloadable-properties.location}") String location) {
this.location = location;
}
/**
* must create a new instance of the property source on every call
*/
@Override
public PropertySource<?> locate(Environment environment) {
try {
return new ResourcePropertySource(location);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
此bean将从可重新加载的.properties文件中读取属性。当您刷新应用程序时,SpringCloudConfig将从磁盘重新加载它
添加运行时,根据需要编辑reloadable.properties
,然后刷新spring上下文。
您可以通过向/refresh
端点发送POST请求,或者在Java中使用contextrefresh
:
@Autowired
ContextRefresher contextRefresher;
...
contextRefresher.refresh();
如果您选择将它与远程git存储库中的属性并行使用,这也应该有效。请查看此答案可能与Nope的不同问题重复谢谢Stefan的回答。我知道您建议我们可以将运行时属性添加到外部化文件中,SpringConfigServer将自动加载它。但我是否有可能实现无需写入文件。是否有一种方法可以执行类似environment.addPorperty(key,Value)的操作,并且它对所有配置客户端都可用。是否可以为项目全局执行该操作,而不是使用@RefreshScope定义bean
org.springframework.cloud.bootstrap.BootstrapConfiguration=your.package.ReloadablePropertySourceLocator
@Autowired
ContextRefresher contextRefresher;
...
contextRefresher.refresh();