2015-06-17 263 views
12

我在我的spring-boot項目中有一個屬性類。彈簧引導:將默認值設置爲可配置屬性

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

    // getter/setter 
} 

現在,我要爲默認值設置爲我application.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引導中使用@ConfigurationProperties類(而不是類型安全配置屬性)執行此操作,其中我的默認值是另一個屬性?

+0

請查看此問題:http://stackoverflow.com/questions/29220498/why-is-configurationproperties-not-overriding-defaults-in-my-case](http://stackoverflow。 com/questions/29220498/why-is-configurationproperties-not-overriding-defaults-in-my-case) –

回答

5

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

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

這解決了我現在的問題。但是,我認爲spring應該像@Value一樣爲它提供支持。 –

+0

我正在尋找如何設置默認值,這是我能找到的唯一答案..但[在這個wiki](https://github.com/spring-projects/spring-boot/wiki/Spring-Boot-配置綁定#默認值)似乎你可以爲你的屬性設置一個默認值,就像你期望的那樣。 – evandongen