我可以在 Spring 引导配置文件中定义系统属性吗?

Can I define System Properties within Spring Boot configuration files?

我的 Spring 启动应用程序有一个 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

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

你可以试试

@Profile("production")
@Component
public class ProductionPropertySetter {

   @PostConstruct
   public void setProperty() {
      System.setProperty("http.maxConnections", "15");
   }

}

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.* 属性映射到系统属性。

请注意,您可能希望尽早设置系统属性,可能会在 Environment 准备好后尽快设置。为此,您可以使用侦听 ApplicationEnvironmentPreparedEventApplicationListener。您的 ApplicationListener 实施应通过 spring.factories.

中的条目注册

您可以将环境注入到指定 bean 的 class 的构造函数中。这允许您在创建 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();
   }
}

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