Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring: how to inject an inline list of strings using @Value annotation [duplicate]

Tags:

java

spring

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?

like image 440
Brice Roncace Avatar asked Dec 09 '14 22:12

Brice Roncace


People also ask

What is the use of @value annotation in spring?

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.

Can we use @value with static?

Afterward, we want to inject its value to an instance variable. That's because Spring doesn't support @Value on static fields.

What is @configuration in spring boot?

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.

How property values can be injected directly into your beans in spring boot?

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.


1 Answers

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.

like image 187
Yuri Avatar answered Oct 12 '22 13:10

Yuri