如何在运行时更新 Spring Boot 应用程序的配置而不重新加载整个 ApplicationContext

How to update configuration of SpringBoot application at runtime without reloading whole ApplicationContext

我想弄清楚如何在 Spring 引导应用程序中动态 update/reload 外部化配置而不重新启动整个应用程序。

大多数建议涉及在更改外部化配置后重新加载 ApplicationContext,但这相当于重新启动整个应用程序,所以这并不是那么有用。

通读 Spring 引导参考文档,我找到了一章 23.7 Typesafe Configuration Properties

如果我理解正确,这允许定义简单的 POJO 类 将您的应用程序(外部化)配置值保存为属性。

至少在理论上,此方案可用于将 bean 仅绑定一次到所需的配置 POJO,并且在配置更改时仅更新 POJO 中的值。组件可以在下次访问 POJO 上的 getter 时轻松获取更改...

但是,我还没有弄清楚如何启用这种行为。当相关配置发生变化时,是否有一些明显的方法可以动态更新用 @ConfigurationProperties 注释的组件?

听起来您正在寻找由 Spring Cloud 提供的 @RefreshScope。来自 Spring Cloud documentation:

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 a DataSource has open connections when the database URL is changed via the Environment, 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.