Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the easiest way to specify a list with values in Spring?

Tags:

java

spring

Assume I'm having a large list of values aa bb cc dd ee ff gg etc., which I need to pass as a constructor in spring

If I need to configure as string array it is easy in spring as we can just specify the values as comma separated as aa, bb, cc etc.,

If I need to configure as list I need to do like below

<bean name="myBean" class="MyClass">
    <constructor-arg>
        <list>
            <value>aa</value>
            <value>bb</value>
            <value>cc</value>
            <value>dd</value>
        </list>
    </constructor-arg>
</bean>

When the number of values increased it occupies a huge lines and it looks ugly.

Could some one please help me how we can pass large values as list in string as constructor?

like image 750
Kathir Avatar asked Jul 20 '12 10:07

Kathir


1 Answers

Spring can automatically convert any comma separated string into a list or array for you:

public class Foo {
   public void setValueList(String[] values) { ... }
}

<bean class="Foo"
      p:valueList="a,b,c,d" />
<bean class="Foo"
      c:_0="a,b,c,d" />
<bean class="Foo">
     <constructor-arg><value>a,b,c,d</value></constructor-arg>
</bean>

In fact, even if there's only 1 value, and no commas in the string, it will still work.

There's no need for the call to org.springframework.util.StringUtils that someone mentioned in another answer.

This words for constructor args as well (c:_0 is shorthand for <constructor-arg index="0"> using the c namespace.

like image 120
Matt Avatar answered Oct 18 '22 21:10

Matt