How to define a bean of String array in Spring (using XML configuration) How to define a bean of String array in Spring (using XML configuration) spring spring

How to define a bean of String array in Spring (using XML configuration)


I don't know if this is done for a reason, but this configuration

<util:list id="someArrayId">    <array>        <value>Tiger</value>        <value>Lion</value>    </array></util:list>

is creating a List bean that contains one element, a Object[] with two String values in it.

If you actually wanted a List with two String values in it, you should have

<util:list id="someArrayId">    <value>Tiger</value>    <value>Lion</value></util:list>

in which case you could modify your field to be annotated with

@Value("#{someArrayId.toArray(new java.lang.String[0])}")

Spring's EL resolver will be able to parse it and execute the corresponding method, which will convert the List to a String[].

Alternatively, remove the @Value annotation and add a @Resource annotated method

@Resource(name = "someArrayId")private void init(List<String> bean) {    this.someArray = bean.toArray(new String[0]);}

I find this cleaner as it's more descriptive.


instead of List, just define array. You can also inject it as configuration to make it less ambiguous. Here another point to note is value-type of array.

<bean id="sampleClass" class="somePackage.SampleClass">    <property name="someArray">        <array value-type="java.lang.String">            <value>Tiger</value>            <value>Lion</value>        </array>    </property></bean>


try like this

@Component("sampleClass")public class SampleClass {    @Value("#{someArrayId.toArray(new String[0])}")    private String[] someArray;    ...<util:list id="someArrayId">    <value>Tiger</value>    <value>Lion</value></util:list>