我可以在 Spring Boot 配置文件中定义系统属性吗? [英] Can I define System Properties within Spring Boot configuration files?

查看:44
本文介绍了我可以在 Spring Boot 配置文件中定义系统属性吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的 Spring Boot 应用程序有一个 application.yml 配置文件,它定义了两个配置文件(如 文档).

I have a single application.yml configuration file for my Spring Boot app that defines two profiles (as described in the documentation).

启用生产配置文件后,我想设置 http.maxConnections 系统属性到自定义值,例如

When the production profile is enabled, I would like to set the http.maxConnections system property to a custom value, e.g.

spring:
    profiles:
        active: dev
---
spring:
    profiles: dev
---
spring:
    profiles: production
http:
    maxConnections: 15

但这实际上并没有设置系统级属性;它似乎只是创建了一个应用程序级属性.在比较通过 http://locahost:8080/env 和 JMX 控制台启动时,我已经验证了这一点/p>

But this doesn't actually set the system level property; it appears to just create an application-level property. I've verified this through both http://locahost:8080/env and a JMX Console when comparing launching by

java -jar -Dspring.profiles.active=production myapp.jar

对比

java -Dhttp.maxConnections=15 myapp.jar

我想我可以在生产"配置文件上创建一个 @Conditional bean,该配置文件基于我的 application.yml 以编程方式调用System.setProperty代码>-定义的属性,但有没有更简单的方法单独通过配置文件?

I suppose I could create a bean that's @Conditional on the "production" profile that programmatically callsSystem.setProperty based on my application.yml-defined property, but is there a simpler way through configuration files alone?

推荐答案

我想我可以在生产"配置文件上创建一个 @Conditional 的 bean,该配置文件根据我的 application.yml 定义的属性以编程方式调用 System.setProperty,但是是否有更简单的方法来单独通过配置文件?

I suppose I could create a bean that's @Conditional on the "production" profile that programmatically callsSystem.setProperty based on my application.yml-defined property, but is there a simpler way through configuration files alone?

我认为这是您最好的选择.Spring Boot 在其 LoggingSystem 中自行完成,其中各种 logging.* 属性映射到系统属性.

I think that's your best bet here. Spring Boot does that itself in its LoggingSystem where various logging.* properties are mapped to System properties.

请注意,您可能希望尽早设置系统属性,可能在 Environment 准备好后立即设置.为此,您可以使用 ApplicationListener 来侦听 ApplicationEnvironmentPreparedEvent.您的 ApplicationListener 实现应该通过 spring.factories 中的条目注册.

Note that you'll probably want to set the system properties as early as possible, probably as soon as the Environment is prepared. To do so, you can use an ApplicationListener that listens for the ApplicationEnvironmentPreparedEvent. Your ApplicationListener implementation should be registered via an entry in spring.factories.

这篇关于我可以在 Spring Boot 配置文件中定义系统属性吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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