在运行时设置/覆盖Spring/Spring Boot属性 [英] Set/override Spring / Spring Boot properties at runtime

查看:195
本文介绍了在运行时设置/覆盖Spring/Spring Boot属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在使用Spring Boot的项目中,我们使用application.properties,但需要基于外部配置来配置其中一些属性(例如日志记录级别的端口号).我们通过API访问配置,因此只有在运行时才能知道.

At the project with Spring Boot we use application.properties but need to configure some of these properties (like port number of logging level) based on an external configuration. We access the configuration via API so it is known only at runtime.

是否有一种方法可以在运行时覆盖或设置某些Spring属性(例如,使用bean),如果可以,该如何实现?

Is there a way to override or set some Spring properties at runtime (for example using a bean) and if yes how can this be achieved?

推荐答案

您可以使用 Spring Cloud Config

仅出于说明目的,这是在运行时查看动态属性覆盖的相对快速的方法:

Just for the purpose of illustration, here's a relatively quick way to see dynamic property overrides at runtime:

首先,为了使您的bean能够获取已更改的属性,您需要使用

First, for your bean to be able to pick up changed properties, you need to annotate it with

@RefreshScope

将spring cloud依赖项添加到您的spring boot应用程序中,例如gradle

Add the spring cloud dependency to your spring boot app, eg for gradle

compile group: 'org.springframework.cloud', name: 'spring-cloud-starter', version: '1.1.1.RELEASE'

(注意,您还需要弹簧启动执行器依赖项.)

( NB You also need the spring boot actuator dependency.)

运行该应用程序后,您可以在以下位置查看当前配置

With the app running, you can view your current config at eg

http://localhost:8080/env

例如,如果您在application.properties中具有属性"my.property",则会看到以下内容:

eg if you have a property 'my.property' in application.properties, you'll see something like:

"applicationConfig: [classpath:/application.properties]": {
  "my.property": "value1",
  etc

要更改该值,请将my.property = value2 POST到/env作为application/x-www-form-urlencoded

To change the value, POST my.property=value2 to /env as application/x-www-form-urlencoded

例如

curl -X POST http://localhost:8080 -d my.property=value2

再次获取/env,您将看到新值显示在经理"部分下

GET /env again and you'll see the new value appears under the "manager" section

要应用更改的属性,请对/refresh执行空的POST.现在,您的bean将具有新值.

To apply the changed properties, do an empty POST to /refresh. Now your bean will have the new value.

这篇关于在运行时设置/覆盖Spring/Spring Boot属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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