1
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;
membersound
  • 81,582
  • 193
  • 585
  • 1,120
  • Does this answer your question? [How to inject a Map using the @Value Spring Annotation?](https://stackoverflow.com/questions/30691949/how-to-inject-a-map-using-the-value-spring-annotation) – İsmail Y. Feb 17 '22 at 09:05

2 Answers2

1

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

so in your case:

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

//dont forget getter that Spring will use to add values.
}

more here

J Asgarov
  • 2,526
  • 1
  • 8
  • 18
  • okay that works, so it's not possible simply ùsing `@Value`, without introducing a separate class? – membersound Feb 17 '22 at 08:25
  • not that i know of, unfortunately. You could of course use @Autowired with some ArrayList, and then in some `@PostConstruct` method (arraylist then as a parameter) populate your map but that is all I can think of – J Asgarov Feb 17 '22 at 08:33
  • did you _try_ the sample that OP asked for? this is not going to work. – Eugene Feb 17 '22 at 08:39
  • you are right i forgot getter that Spring uses to add values as well as to initialize the field. Setter is actually not necessary. Was writing from top of my head but thanks for catching - update my answer to not confuse anyone. – J Asgarov Feb 17 '22 at 09:19
  • excellent! I removed my down-vote, thank you for getting back. – Eugene Feb 17 '22 at 09:29
1

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.

Eugene
  • 117,005
  • 15
  • 201
  • 306