簡體   English   中英

Spring-boot:將默認值設置為可配置屬性

[英]Spring-boot: set default value to configurable properties

我的spring-boot項目中有一個屬性類。

@Component
@ConfigurationProperties(prefix = "myprefix")
public class MyProperties {
    private String property1;
    private String property2;

    // getter/setter
}

現在,我想在property.properties文件中為property1設置一些其他屬性的默認值。 類似於以下示例使用@Value

@Value("${myprefix.property1:${somepropety}}")
private String property1;

我知道我們可以像下面的示例一樣分配靜態值,其中“默認值”被指定為property默認值,

@Component
@ConfigurationProperties(prefix = "myprefix")
public class MyProperties {
    private String property1 = "default value"; // if it's static value
    private String property2;

    // getter/setter
}

如何在spring boot中使用@ConfigurationProperties類(而不是類型安全的配置屬性)來執行此操作,其中我的默認值是另一個屬性?

檢查是否在MyProperties類中使用@PostContruct設置了property1。 如果不是,您可以將其分配給另一個屬性。

@PostConstruct
    public void init() {
        if(property1==null) {
            property1 = //whatever you want
        }
    }

在spring-boot 1.5.10(可能更早)中,設置默認值按照建議的方式工作。 例:

@Component
@ConfigurationProperties(prefix = "myprefix")
public class MyProperties {

  @Value("${spring.application.name}")
  protected String appName;
}

@Value默認值僅在未在您自己的屬性文件中重寫時使用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM