Spring Boot @ConfigurationProperties - Change property key

Doe Johnson :

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!

Amit Phaltankar :

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;
    }
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=75294&siteId=1