我可以在Spring Boot配置文件中定义系统属性吗?
我有一个针对我的Spring Boot应用application.yml
配置文件,它定义了两个配置文件(如文档中所述)。
启用生产配置文件后,我想将http.maxConnections
系统属性设置为自定义值,例如
spring: profiles: active: dev --- spring: profiles: dev --- spring: profiles: production http: maxConnections: 15
但这实际上并没有设置系统级属性; 它似乎只是创建一个应用程序级属性。 我在比较启动时通过http:// locahost:8080 / env和JMX控制台validation了这一点
java -jar -Dspring.profiles.active=production myapp.jar
与
java -Dhttp.maxConnections=15 myapp.jar
我想我可以在“生产”配置文件上创建一个@Conditional
的bean,它根据我的application.yml
-defined属性以编程方式调用System.setProperty
,但是单独通过配置文件有更简单的方法吗?
我想我可以在“生产”配置文件上创建一个@Conditional的bean,它根据我的application.yml-defined属性以编程方式调用System.setProperty,但是单独通过配置文件有一种更简单的方法吗?
我认为这是你最好的选择。 Spring Boot在其LoggingSystem
中自行完成,其中各种logging.*
属性映射到System属性。
请注意,您可能希望尽早设置系统属性,可能只要Environment
准备就绪。 为此,您可以使用侦听ApplicationEnvironmentPreparedEvent
。 应通过spring.factories
的条目注册ApplicationListener
实现。
你可以试试。
@Profile("production") @Component public class ProductionPropertySetter { @PostConstruct public void setProperty() { System.setProperty("http.maxConnections", 15); } }
您可以将环境注入到指定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中的PropertyPlaceholderConfigurer来处理属性文件