Home > Blockchain >  How to inject Spring application.properties grouped by prefix?
How to inject Spring application.properties grouped by prefix?

Time:02-17

foo.bar.one=1
foo.bar.two=2
foo.bar.n=n

It is possible to inject all properties from foo.bar.* into one field?

Pseudocode:

@Value("${foo.bar.*}")
private Map<String, Object> foobar;

CodePudding user response:

Use @ConfigurationProperties("prefix") (at a class level)

so in your case:

@ConfigurationProperties("foo")
public class SomeClass {
private Map<String, Object> bar;  //the name of the map can serve as a second part of prefix
...
}

more here

CodePudding user response:

First of all, no, you can not do what you want with @Value. You should not be using @Value anyway, at least one reason is that it does not support relaxed binding.

Second, @ConfigurationProperties will work, but you have to be very careful on how you name things. Taken your example literally, you would need:

@ConfigurationProperties(prefix = "foo")
public class Props {

    private Map<String, String> bar = new HashMap<>();

    public Map<String, String> getBar() {
        return bar;
    }

    public void setBar(Map<String, String> bar) {
        this.bar = bar;
    }
}

Notice the prefix=foo and property named bar.

  • Related