25

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 ?

Ashvin Kanani
  • 831
  • 2
  • 14
  • 22
  • Please, view this question: [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) – Tadeu Jr. Aug 25 '16 at 13:59

2 Answers2

8

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
        }
    }
jst
  • 1,697
  • 1
  • 12
  • 13
  • 5
    This solved my problem for now. But, I think spring should provide support for the same just like @Value. – Ashvin Kanani Jun 23 '15 at 04:04
  • 1
    I was searching on how to set defaults and this was about the only answer I could find .. but [on this wiki](https://github.com/spring-projects/spring-boot/wiki/Spring-Boot-Configuration-Binding#default-value) it seems you can set a default value for your property like you would expect. – evandongen Nov 01 '17 at 08:28
4

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.

Andy Brown
  • 11,766
  • 2
  • 42
  • 61
  • Thank you, yet how would one parse the parameter values form the properties file this way? E.g., how can I ensure that a specific value is indeed an Integer and in the range of 5-8? – Xenonite Apr 05 '19 at 09:55
  • @Xenonite: Add `@Validated` to the class and then use the existing `javax.validation.constraints.*` annotations on the fields or create some of your own if what's provided is insufficient. – Andy Brown Apr 05 '19 at 14:44
  • It is not recommended to mix both behaviors. – lucasvc Apr 09 '20 at 08:08