我正在开发Spring Integration/Boot应用程序。我正在使用多文档application.yml
(src/main/resources/application.yml)为多个配置类(使用@ConfigurationProperties注释)设置默认值。 Applicaiton.yml带有默认值,其中一些需要被覆盖,具体取决于环境。我打开使用Java系统属性(-D ... = ...),弹簧“属性”(--... = ...),或者最好是一个位于外部的yaml文件Jar,在一个目录中。覆盖@ConfigurationProperties
Application.yml有4个文档,每个文档对应一个不同的配置类。让我们只专注于SERVERCONFIG:
@Configuration
@EnableConfigurationProperties
@ConfigurationProperties(locations = "classpath:application.yml", prefix = "server")
public class ServerConfig {
private Integer port;
private String address;
public Integer getPort() {
return port;
}
public void setPort(Integer port) {
this.port = port;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
Application.yml:
server:
address: ::1
port: 8080
---
注意我是如何在注释中指定locations
。这加载application.yml并成功使用这些值,但我无法弄清楚如何覆盖它们(例如-Dserver.port = 7777或--server.port = 7777)。如果我删除locations = ...
,那么我可以使用`-Dserver.port = 7777,但application.yml中的默认值永远不会被加载,所以我必须指定每个值作为命令行参数。
我已经阅读了https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html很多次,我不明白为什么我不能在配置注释中保留locations = 'application.yml'
,并有选择地用系统属性覆盖。
有谁知道如何做到这一点?
你为什么要用你自己的类来替换内置的服务器属性? https://github.com/spring-projects/spring-boot/blob/v1.3.5.RELEASE/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/ServerProperties.java也许它冲突 – zapl
@zapl:我甚至不知道存在,但我认为它不适用于Spring集成或servlet外部。无论如何,我有3个配置类用于特定于应用程序的配置,可能会遇到同样的问题。这对于人们来说是最简单的。 – fandingo
糟糕,这只是spring-boot-web的一部分。它可能是https://github.com/spring-projects/spring-boot/issues/5111?换句话说,'location'不应该被使用,但它应该没有它。 – zapl