8
votes

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?

1
The answer hasn't helped yet? If it helped - then you could mark the question as answered. BTW comment below also helps.Yuri

1 Answers

29
votes

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.