我正在开发一个/Boot应用程序。我使用一个多文档application.yml (src/main/resources/application.yml)为几个配置类(带有@ConfigurationProperties注释)设置默认值。Applicaiton.yml附带缺省值,根据环境的不同,需要重写其中一些默认值。
我可以使用(-D...=.)、Spring " properties“(--=.),也可以使用目录中位于Jar之外的yaml文件。
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'留在配置注释中,并有选择地用系统属性覆盖。
有人知道怎么做吗?
发布于 2016-05-16 17:08:24
叹一口气。这是应用程序启动的一个问题--这是由于我在和Spring之间的混淆造成的。
我的主要方法是:
@SpringBootApplication
public class Main {
public static void main(String... args) {
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext("org.fandingo.blah.blah");
ctx.registerShutdownHook();
}我的理解是,这就是如何启动仅限于Spring的应用程序(当然,假设是JavaConfig )。问题是,加载YAML属性是Spring特性。切换出使用Spring方法的主要方法解决了这个问题:
@SpringBootApplication
public class Main {
public static void main(String... args) {
SpringApplication app = new SpringApplication(Main.class);
app.setRegisterShutdownHook(true);
app.run(args);
}
}春天真是他妈的复杂而神秘。为什么Spring集成和Boot不能自然地合作是我无法理解的。
https://stackoverflow.com/questions/37218368
复制相似问题