如何在运行时更新SpringBoot应用程序的配置,而不重新加载整个ApplicationContext [英] How to update configuration of SpringBoot application at runtime without reloading whole ApplicationContext

查看:5133
本文介绍了如何在运行时更新SpringBoot应用程序的配置,而不重新加载整个ApplicationContext的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想弄清楚如何在Spring Boot应用程序中动态更新/重新加载外部化配置,而无需重新启动整个应用程序。

I am trying to figure out how can I dynamically update/reload externalized configuration in a Spring Boot application without restarting the whole application.

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

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.

通过SpringBoot参考文档,我发现一个第23.7章类型安全配置属性

Reading through SpringBoot reference documentation, I found a chapter 23.7 Typesafe Configuration Properties.

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

If I understand it correctly, this allows to define simple POJO classes that will hold your application (externalized) configuration values as attributes.

至少在理论上,这个方案可以用来绑定bean一次到所需的配置POJO和配置更改只是更新POJO中的值。组件可以很容易地获取更改下次访问getjo在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...

但是,我还没有设法找出如何启用这种类型的行为。当相关配置发生变化时,是否有一些非常明显的方式来动态更新用 @ConfigurationProperties 注释的组件?

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?

推荐答案

听起来你正在寻找由Spring Cloud提供的 @RefreshScope 。从 Spring Cloud文档

It sounds like you're looking for @RefreshScope which is provided by Spring Cloud. From the Spring Cloud documentation:


A @Bean 标记为 @RefreshScope 将有配置更改时得到特殊处理。这解决了有状态bean的问题,只有当它们被初始化时才注入它们的配置。例如,如果通过 Environment 更改数据库URL时 DataSource 已打开连接,我们可能希望这些连接能够完成他们正在做什么。然后下次有人从池中借用连接时,他会获得一个带有新URL的连接。

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.

这篇关于如何在运行时更新SpringBoot应用程序的配置,而不重新加载整个ApplicationContext的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆