【问题标题】:Set/override Spring / Spring Boot properties at runtime在运行时设置/覆盖 Spring / Spring Boot 属性
【发布时间】:2015-03-11 05:44:45
【问题描述】:

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

有没有办法在运行时覆盖或设置一些 Spring 属性(例如使用 bean),如果可以,如何实现?

【问题讨论】:

标签: spring spring-boot


【解决方案1】:

你可以用Spring Cloud Config做到这一点

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

首先,为了让您的 bean 能够获取更改的属性,您需要对其进行注释

@RefreshScope

将 Spring Cloud 依赖项添加到您的 Spring Boot 应用程序中,例如 gradle

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

(请注意,您还需要 spring boot 执行器依赖项。)

随着应用程序的运行,您可以在例如查看当前配置

http://localhost:8080/env

例如,如果您在 application.properties 中有一个属性“my.property”,您会看到如下内容:

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

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

例如

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

再次获取 /env,您将看到新值出现在“管理器”部分下

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

【讨论】:

  • 我遇到了这个异常:org.springframework.web.HttpRequestMethodNotSupportedException: Request method 'POST' not supported
  • hi @SandeepKumar 添加此属性以在 /env management.endpoint.env.post.enabled=true 上启用发布请求
【解决方案2】:

您可以使用系统属性来传递变量吗?如果您配置PropertyPlaceholderConfigurer,您可以设置系统属性与文件属性的优先级。

例如:

@Bean public PropertyPlaceholderConfigurer placeHolderConfigurer() {
    PropertyPlaceholderConfigurer props = new PropertyPlaceholderConfigurer()
    props.setSystemPropertiesMode( PropertyPlaceholderConfigurer.SYSTEM_PROPERTIES_MODE_OVERRIDE )
    props.setLocations(new 
PathMatchingResourcePatternResolver().getResources("classpath:/**.properties"));
    props
}

上面会加载你的 .properties 文件,但是我们首先将优先级设置为系统变量,所以如果你设置了一个系统变量,它将覆盖配置中的相同变量。

另外,查看the docs,Spring 建议在您的环境中定义搜索顺序:

[PropertyPlaceholderConfigurer 仍然适合在什么情况下使用] 现有配置使用“systemPropertiesMode”和/或“systemPropertiesModeName”属性。鼓励用户 不再使用这些设置,而是配置属性 通过容器环境的源搜索顺序;然而, 功能的精确保存可以通过继续保持 使用 PropertyPlaceholderConfigurer。

希望以上其中一项能解决您的需求?

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-06-22
  • 2016-01-16
  • 2011-04-17
  • 2018-07-12
  • 2020-12-23
相关资源
最近更新 更多