Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring-boot: set default value to configurable properties

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 ?

like image 826
Ashvin Kanani Avatar asked Jun 17 '15 04:06

Ashvin Kanani


People also ask

How do I set default property value in spring boot?

To set a default value for primitive types such as boolean and int, we use the literal value: @Value("${some. key:true}") private boolean booleanWithDefaultValue; @Value("${some.

What is the use of @configuration in spring boot?

Spring @Configuration annotation is part of the spring core framework. Spring Configuration annotation indicates that the class has @Bean definition methods. So Spring container can process the class and generate Spring Beans to be used in the application.

How do I set environment specific properties in spring boot?

Environment-Specific Properties File. If we need to target different environments, there's a built-in mechanism for that in Boot. We can simply define an application-environment. properties file in the src/main/resources directory, and then set a Spring profile with the same environment name.


2 Answers

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         }     } 
like image 69
jst Avatar answered Sep 25 '22 06:09

jst


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.

like image 23
Andy Brown Avatar answered Sep 22 '22 06:09

Andy Brown