Spring.properties file: get element as array

I am loading property attributes from a .properties file using Spring as follows:

 file: elements.properties base.module.elementToSearch=1 base.module.elementToSearch=2 base.module.elementToSearch=3 base.module.elementToSearch=4 base.module.elementToSearch=5 base.module.elementToSearch=6 

Spring xml file

 file: myapplication.xml <bean id="some" class="com.some.Class"> <property name="property" value="#{base.module.elementToSearch}" /> </bean> 

And my .java class

 file: Class.java public void setProperty(final List<Integer> elements){ this.elements = elements; } 

But when debugging, the parameter elements receive only the last element in the list, therefore there is a list of one element with a value of "6", and not a list of 6 elements.

I tried other approaches, such as adding only the value #{base.module} , but then it did not find any parameter in the properties file.

The workaround is to have a comma separated list in element.properties file, for example:

 base.module.elementToSearch=1,2,3,4,5,6 

and use it as a String and parse it, but is there a better solution?

+48
java spring placeholder properties-file
Jun 02 '11 at 9:50 a.m.
source share
3 answers

If you define your array in a properties file, for example:

 base.module.elementToSearch=1,2,3,4,5,6 

You can load such an array into your Java class as follows:

  @Value("${base.module.elementToSearch}") private String[] elementToSearch; 
+102
Jun 20 '11 at 13:50
source share

Here is an example of how you can do this in Spring 4.0+

application.properties content:

 some.key=yes,no,cancel 

Java Code:

 @Autowire private Environment env; ... String[] springRocks = env.getProperty("some.key", String[].class); 
+12
Nov 26 '15 at 17:20
source share

And add another separator other than comma, you can also use it.

 @Value("#{'${my.config.values}'.split(',')}") private String[] myValues; // could also be a List<String> 

and

in your application properties you could

 my.config.values=value1, value2, value3 
+11
Aug 19 '16 at 13:04 on
source share



All Articles