【问题标题】:Can I define System Properties within Spring Boot configuration files?我可以在 Spring Boot 配置文件中定义系统属性吗?
【发布时间】:2016-08-22 02:22:14
【问题描述】:

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

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

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

但这实际上并没有设置系统级属性;它似乎只是创建了一个应用程序级属性。在比较由

启动时,我已经通过 http://locahost:8080/env 和 JMX 控制台验证了这一点
java -jar -Dspring.profiles.active=production myapp.jar

对比

java -Dhttp.maxConnections=15 myapp.jar

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

【问题讨论】:

    标签: java spring-boot system-properties


    【解决方案1】:

    你可以试试。

    @Profile("production")
    @Component
    public class ProductionPropertySetter {
    
       @PostConstruct
       public void setProperty() {
          System.setProperty("http.maxConnections", "15");
       }
    
    }
    

    【讨论】:

    • 问题是,如果你想改变这个,你需要重新部署,否则你可以修改它并重新启动你的应用程序
    • @Palcente 是的,这是有道理的。我相信您可以将属性放在application-production.yml 中,这些属性将在production 配置文件中使用。
    • System.setProperty("http.maxConnections", "15");// 此处不允许使用 int :))
    【解决方案2】:

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

    我认为这是你最好的选择。 Spring Boot 本身在其 LoggingSystem 中执行此操作,其中各种 logging.* 属性映射到系统属性。

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

    【讨论】:

      【解决方案3】:

      您可以将环境注入到指定 bean 的类的构造函数中。这允许您在创建 bean 之前将应用程序属性写入系统属性。

      @Configuration
      public class ApplicationBeans {
      
         @Autowired
         public ApplicationBeans(Environment environment) {
            // set system properties before the beans are being created.
            String property = "com.application.property";
            System.getProperties().setProperty(property, environment.getProperty(property));
         }
      
         /**
          * Bean that depends on the system properties
          */
         @Bean
         public SomeBean someBean() {
            return new SomeBean();
         }
      }
      

      【讨论】:

        【解决方案4】:

        您还可以使用 org.springframework.beans.factory.config 中的 PropertyPlaceholderConfigurer 来处理您的属性文件

        【讨论】:

          猜你喜欢
          • 2014-12-21
          • 2013-05-07
          • 2012-03-15
          • 1970-01-01
          • 1970-01-01
          • 2019-06-28
          • 2011-12-02
          • 2020-06-19
          • 1970-01-01
          相关资源
          最近更新 更多