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

Java 我可以在Spring引导配置文件中定义系统属性吗?,java,spring-boot,system-properties,Java,Spring Boot,System Properties,我有一个用于Spring Boot应用程序的application.yml配置文件,它定义了两个配置文件(如中所述) 启用生产配置文件后,我希望将系统属性设置为自定义值,例如 spring: profiles: active: dev --- spring: profiles: dev --- spring: profiles: production http: maxConnections: 15 但这实际上并没有设置系统级属性;它似乎只是创建

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

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

spring:
    profiles:
        active: dev
---
spring:
    profiles: dev
---
spring:
    profiles: production
http:
    maxConnections: 15
但这实际上并没有设置系统级属性;它似乎只是创建了一个应用程序级属性。我已经通过和JMX控制台验证了这一点

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

java -Dhttp.maxConnections=15 myapp.jar
我想我可以在“生产”配置文件上创建一个bean,该bean基于我的
应用程序.yml
定义的属性,以编程方式调用
System.setProperty
,但是否有一种更简单的方法单独处理配置文件?

您可以尝试

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

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

}
我想我可以创建一个bean,它以“production”配置文件为条件,根据application.yml定义的属性以编程方式调用system.setProperty,但是有没有一种更简单的方法来单独处理配置文件呢

我想这是你最好的选择。Spring Boot在其
LoggingSystem
中实现了这一点,其中各种
logging.*
属性映射到系统属性


请注意,您可能希望尽早设置系统属性,可能是在
环境
准备好之后。为此,您可以使用侦听
ApplicationEnvironmentPreparedEvent
ApplicationListener
。您的
ApplicationListener
实现应该通过
spring.Factorys中的一个条目注册。您可以将环境注入到指定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();
   }
}

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

问题是,如果要更改此文件,您需要重新部署,否则您可以修改它并重新启动您的app@Palcente是的,这是有道理的。我相信您可以将属性放入
应用程序production.yml
中,该属性将用于
profile.System.setProperty(“http.maxConnections”,“15”);/此处不允许使用int:))