首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >重写@ConfigurationProperties

重写@ConfigurationProperties
EN

Stack Overflow用户
提问于 2016-05-13 19:54:32
回答 1查看 4.4K关注 0票数 1

我正在开发一个/Boot应用程序。我使用一个多文档application.yml (src/main/resources/application.yml)为几个配置类(带有@ConfigurationProperties注释)设置默认值。Applicaiton.yml附带缺省值,根据环境的不同,需要重写其中一些默认值。

我可以使用(-D...=.)、Spring " properties“(--=.),也可以使用目录中位于Jar之外的yaml文件。

Application.yml有4个文档,每个文档对应一个不同的配置类。让我们关注一下ServerConfig:

代码语言:javascript
复制
@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:

代码语言:javascript
复制
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'留在配置注释中,并有选择地用系统属性覆盖。

有人知道怎么做吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-05-16 17:08:24

叹一口气。这是应用程序启动的一个问题--这是由于我在和Spring之间的混淆造成的。

我的主要方法是:

代码语言:javascript
复制
 @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方法的主要方法解决了这个问题:

代码语言:javascript
复制
 @SpringBootApplication
public class Main {
    public static void main(String... args) {
        SpringApplication app = new SpringApplication(Main.class);
        app.setRegisterShutdownHook(true);
        app.run(args);
    }
}

春天真是他妈的复杂而神秘。为什么Spring集成和Boot不能自然地合作是我无法理解的。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/37218368

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档