8

How do I inject a list of string values using the @Value annotation. I'm using Spring 4.1.2.

I've tried:

@Value(value = "top, person, organizationalPerson, user")
private List<String> userObjectClasses

and then based on the spring el documentation for inline lists:

@Value(value = "{top, person, organizationalPerson, user}")
private List<String> userObjectClasses

These attempts only inject a string literal of the value given as the only element in the list.

EDIT

In this case, I'd like to be able to simply hard-code the values rather than read from a property file. This approach seems a little less smelly than:

private List<String> userObjectClasses = Arrays.asList(new String[] {"top", "person", "organizationalPerson", "user"});

In the past, I've used spring's XML configuration to wire up beans, and in that case I could do (assuming the bean had a public setter for the userObjectClasses property):

<property value="userObjectClass">
  <list>
    <value>top</value>
    <value>person</value>
    <value>organizationalPerson</value>
    <value>user</value>
  </list>
</property>

Is there an analog to this when using annotation based configuration?

Brice Roncace
  • 10,110
  • 9
  • 60
  • 69
  • The answer hasn't helped yet? If it helped - then you could mark the question as answered. BTW comment below also helps. – Yuri Jun 15 '15 at 09:15

1 Answers1

29

list.of.strings=first,second,third took from properties file for e.g.

Then using SpEL:

 @Value("#{'${list.of.strings}'.split(',')}") 
 private List<String> list;

EDIT

Then I don't think that you need to use annotation for such type of tasks. You could do all work just like you've menitioned or in the @PostConstruct in order to initialize some fields.

Yuri
  • 1,748
  • 2
  • 23
  • 26
  • 15
    The spring convertion service will perform the split for you if your reference is an `array` or `Collection`, so you don't need that ugly expression: just `@Value("${list.of.strings}")` – Costi Ciudatu Dec 09 '14 at 23:34
  • @CostiCiudatu how does it know which delimiter to split on? does this only work for a `,`? – Erin Drummond May 23 '16 at 21:16
  • 3
    @ErinDrummond It uses [StringUtils.commaDelimitedListToStringArray](http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/util/StringUtils.html#commaDelimitedListToStringArray-java.lang.String-) internally; so yes, it relies on the comma-separated format. – Costi Ciudatu May 23 '16 at 22:32
  • 1
    @CostiCiudatu how to enable spring convertion service? not working for me by default. spring4 – Daniel Hári Feb 01 '18 at 13:01