java 如何在不重新加载整个 ApplicationContext 的情况下在运行时更新 SpringBoot 应用程序的配置
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/33365874/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to update configuration of SpringBoot application at runtime without reloading whole ApplicationContext
提问by Roland Tepp
I am trying to figure out how can I dynamically update/reload externalized configuration in a Spring Boot application without restarting the whole application.
我想弄清楚如何在不重新启动整个应用程序的情况下动态更新/重新加载 Spring Boot 应用程序中的外部化配置。
Most of the advice involves reloading ApplicationContext after changing the externalized configuration, but that is equivalent to restarting the entire application, so this is not really all that useful.
大多数建议涉及在更改外部化配置后重新加载 ApplicationContext,但这相当于重新启动整个应用程序,因此这并不是真正有用。
Reading through SpringBoot reference documentation, I found a chapter 23.7 Typesafe Configuration Properties.
通读 SpringBoot 参考文档,发现一章23.7 Typesafe Configuration Properties。
If I understand it correctly, this allows to define simple POJO classes that will hold your application (externalized) configuration values as attributes.
如果我理解正确的话,这允许定义简单的 POJO 类,这些类将您的应用程序(外部化)配置值保存为属性。
In theory at least, this scheme could be used to bind beans only once to the required configuration POJO and upon configuration change just update the values in the POJO. Components could easily pick up the changes next time they access getters on the POJO...
至少在理论上,这个方案只能用于将 bean 绑定到所需的配置 POJO 一次,并且在配置更改时只更新 POJO 中的值。组件下次访问 POJO 上的 getter 时可以轻松地获取更改...
However, I have yet not managed to figure out how to enable this type of behavior. Is there some glaringly obvious way to dynamically update components annotated with @ConfigurationProperties
when relevant configuration has changed?
但是,我还没有弄清楚如何启用这种类型的行为。@ConfigurationProperties
当相关配置发生变化时,是否有一些明显的方法可以动态更新注释的组件?
回答by Andy Wilkinson
It sounds like you're looking for @RefreshScope
which is provided by Spring Cloud. From the Spring Cloud documentation:
听起来您正在寻找@RefreshScope
Spring Cloud 提供的内容。从Spring Cloud 文档:
A Spring
@Bean
that is marked as@RefreshScope
will get special treatment when there is a configuration change. This addresses the problem of stateful beans that only get their configuration injected when they are initialized. For instance if aDataSource
has open connections when the database URL is changed via theEnvironment
, we probably want the holders of those connections to be able to complete what they are doing. Then the next time someone borrows a connection from the pool he gets one with the new URL.
当配置更改时
@Bean
,标记为的Spring@RefreshScope
将得到特殊处理。这解决了有状态 bean 的问题,这些 bean 仅在初始化时注入其配置。例如,如果在DataSource
通过 更改数据库 URL 时有打开的连接Environment
,我们可能希望这些连接的持有者能够完成他们正在做的事情。然后下次有人从池中借用连接时,他会得到一个带有新 URL 的连接。