我正在尝试在运行时重新加载应用程序的配置。配置位于yaml文件中,与@ConfigurationProperties
的绑定按预期工作。接下来是。我想在yaml改变时重新加载配置。或者我正在检查@Scheduled
文件是否已更改。
我想避免运行第二台服务器进行Environment
更新。我有两个问题:
ConfigurableEnvironment
可能?Spring cloud配置文档声明:
EnvironmentChangeEvent
涵盖了一大类刷新用例,只要您实际可以对Environment
进行更改并发布事件(这些API是公共的并且是Spring Spring的一部分)< / p>
因此发布活动正在发挥作用,但我不了解如何实际更新属性。
答案 0 :(得分:1)
对此进行了相当多的讨论:如何在不使用任何配置服务器的情况下刷新属性。 here上有一个Dave Syer帖子,可以为您带来一些启发-但仍然不言自明。
以下是最自然的spring-boot / -cloud方法(如on spring-cloud-config github所述):
@Component
@ConfigurationProperties("ignored")
@RefreshScope
public class Config {
private List<String> path;
public List<String> getPath() {
return path;
}
public void setPath(List<String> path) {
this.path = path;
}
}
由于@RefreshScope
和@ConfigurationProperties
之间的某些代理问题,此方法不起作用-两种注释都导致Bean代理之间存在矛盾。
因此,我从春天的角度开始研究它。可通过Environment
访问propertySources,因此您可以通过以下方式访问和修改它们:
final String propertySourceName = "externalConfiguration";
// name of propertySource as defined by
// @PropertySource(name = "externalConfiguration", value = "${application.config.location}")
ResourcePropertySource propertySource = new ResourcePropertySource(propertySourceName, new FileSystemResource(file));
MutablePropertySources sources = ctx.getEnvironment().getPropertySources();
sources.replace(propertySourceName, propertySource);
我的用例基于“用户编辑文件”,因此刷新的属性基于FileSystemWatcher,后者使propertySources发生了变化。为了使配置Bean正确提取源,该Bean的范围需要是一个原型-在每次调用时都正确地重建。
完整的示例是available as a gist。不包括任何配置服务器。希望有帮助