Spring-boot: set default value to configurable properties

此生再无相见时 提交于 2019-12-05 09:54:04

问题


I have a properties class below in my spring-boot project.

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

    // getter/setter
}

Now, I want to set default value to some other property in my application.properties file for property1. Similar to what below example does using @Value

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

I know we can assign static value just like in example below where "default value" is assigned as default value for property,

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

    // getter/setter
}

How to do this using @ConfigurationProperties class (rather typesafe configuration properties) in spring boot where my default value is another property ?


回答1:


Check if property1 was set using a @PostContruct in your MyProperties class. If it wasn't you can assign it to another property.

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



回答2:


In spring-boot 1.5.10 (and possibly earlier) setting a default value works as-per your suggested way. Example:

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

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

The @Value default is only used if not overridden in your own property file.



来源:https://stackoverflow.com/questions/30882541/spring-boot-set-default-value-to-configurable-properties

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!