Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Boot @ConfigurationProperties - Change property key

I have an interesting use case where the field name that is used in a class annotated with @ConfigurationProperties should be different from the corresponding key used in the (yaml) configuration file:

@ConfigurationProperties("foo")
class ConfProps {

    private List<SomePojo> bar = new ArrayList<>();

    // getter, setter

}

This will "look out for" foo.bar. Is it possible to map the field bar to a different property key?

I read the the docs and some related articles, but nothing ...

To me it seems that either it's because it is absolutely trivial or this is some kind of non-goal.

Thanks in advance!

like image 501
Doe Johnson Avatar asked Oct 24 '18 04:10

Doe Johnson


People also ask

How do I change spring boot properties?

To change properties in a file during runtime, we should place that file somewhere outside the jar. Then we tell Spring where it is with the command-line parameter –spring. config. location=file://{path to file}.

Can we change application properties in spring boot?

Spring boot provides command line configuration called spring.config.name using that we can change the name of application. properties. Here properties file name will be my-config.

How do I refresh application properties in spring boot?

For Reloading properties, spring cloud has introduced @RefreshScope annotation which can be used for refreshing beans. Spring Actuator provides different endpoints for health, metrics. but spring cloud will add extra end point /refresh to reload all the properties.


1 Answers

Well you can't have different config key and mapping property name. That's how spring resolves the auto-mapping.

However, if having a different property field is so essential for you have can have a hack.

Put a dummy setter like this.

Property key: foo.bar

Config class:

@ConfigurationProperties("foo")
class ConfProps {

    private List<SomePojo> differentlyNamedList = new ArrayList<>();

    // getter, setter

    public void setBar(List<SomePojo> bar){
       this.differentlyNamedList = bar;
    }
}
like image 168
Amit Phaltankar Avatar answered Nov 14 '22 21:11

Amit Phaltankar