17
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://            www.springframework.org/schema/beans/spring-beans.xsd">

   <bean id="test" class="com.Test">
        <constructor-arg>
            <list>
                <value>aa</value>
                <value>bb</value>
                <value>cc</value>
            </list>
        </constructor-arg>
    </bean>
</beans>

This is my current XML. If only Test took a List - everything would be fine.

The problem is that Test takes an array of strings.

How to do it in Spring?

Queequeg
  • 2,824
  • 8
  • 39
  • 66

4 Answers4

21

You should use:

<constructor-arg>
    <array>
        <value>aa</value>
        <value>bb</value>
        <value>cc</value>
    </array>
</constructor-arg>

An array can contain multiple inner bean, ref, collection, or value elements. This configuration element will always result in an array, even when being defined e.g. as a value for a map with value type Object.

Also you can specify a value type which you will be passing:

<array value-type="java.lang.String">
  <value>aa</value>
  <value>bb</value>
  <value>cc</value>
</array>

value-type

The default Java type for nested values. Must be a fully qualified class name.

Paulius Matulionis
  • 23,085
  • 22
  • 103
  • 143
4

instead of <list> use

<array>
  <value>aa</value>
  <value>bb</value>
  <value>cc</value>
</array>
Evgeniy Dorofeev
  • 133,369
  • 30
  • 199
  • 275
3

With Spring version 3.2.8 you can use

<constructor-arg>
    <list>
        <value>aa</value>
        <value>bb</value>
        <value>cc</value>
    </list>
</constructor-arg>

without problems.

JulianG
  • 1,551
  • 1
  • 19
  • 29
2

If the constructor has String[] as a parameter (which also includes String...), you can provide a comma-separated list:

<constructor-arg value="Hindustan Moters,Tata Moters,Ashoka Leyland"/>

This is notoriously used to instantiate e.g. H2 DB server as a bean. See e.g. here.

Not sure which version introduced that.

Ondra Žižka
  • 43,948
  • 41
  • 217
  • 277