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?
Spring @Value annotation is used to assign default values to variables and method arguments. We can read spring environment variables as well as system variables using @Value annotation. Spring @Value annotation also supports SpEL.
Afterward, we want to inject its value to an instance variable. That's because Spring doesn't support @Value on static fields.
Spring @Configuration annotation is part of the spring core framework. Spring Configuration annotation indicates that the class has @Bean definition methods. So Spring container can process the class and generate Spring Beans to be used in the application.
Property values can be injected directly into your beans using the @Value annotation, accessed via Spring's Environment abstraction or bound to structured objects via @ConfigurationProperties . Spring Boot uses a very particular PropertySource order that is designed to allow sensible overriding of values.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With