Reading dynamic property list in spring bean

I searched but cannot find these steps. Hope I miss something obvious.

I have a properties file with the following contents:

machines=A,B 

I have another file similar to this one but having a different number of elements in the machine element, for example:

 machines=B,C,D 

My question is how to load this variable variable machine variable into a bean in my spring configuration in a general way?

something like that:

 <property name="machines" value="${machines}"/> 

where machines is an array or list in my java code. I can define it, but I want to, can I understand how to do it.

Basically, I would prefer spring to parse and bind each value to a list item instead of having to write something that is read on the full line of the machine and independently parse (with a comma separator) each value into an array or list. Is there an easy way to do this that I am missing?

+27
spring dynamic javabeans
Mar 11 2018-11-11T00:
source share
4 answers

You can take a look at the Spring StringUtils class. It has a number of useful methods for converting a comma-separated list to an array of Set or String. You can use any of these utility methods using the Spring factory -method framework to inject the parsed value into your bean. Here is an example:

 <property name="machines"> <bean class="org.springframework.util.StringUtils" factory-method="commaDelimitedListToSet"> <constructor-arg type="java.lang.String" value="${machines}"/> </bean> </property> 

In this example, the value for "machines" is loaded from the properties file.

If the existing utility method does not meet your needs, it’s quite simple to create your own. This method allows you to execute any static method.

+31
Mar 11 '11 at 15:00
source share

Spring EL is simplified. Java:

 List <String> machines; 

Context:

 <property name="machines" value="#{T(java.util.Arrays).asList('${machines}')}"/> 
+19
Mar 14 '12 at 13:40
source share

If you make the "machine" property an array of String, spring will do it automatically for you

 machines=B,C,D <property name="machines" value="${machines}"/> public void setMachines(String[] test) { 
+16
Jul 11 2018-11-11T00:
source share

Since Spring 3.0, you can also read in the list of values ​​using the @Value annotation.

Property File:

 machines=B,C,D 

Java Code:

 import org.springframework.beans.factory.annotation.Value; @Value("#{'${machines}'.split(',')}") private List<String> machines; 
+4
Nov 04 '13 at 8:12
source share



All Articles