guerda guerda - 3 months ago 22
Java Question

How to define a List bean in Spring?

I'm using Spring to define stages in my application. It's configured that the necessary class (here called

Configurator
) is injected with the stages.

Now I need the List of Stages in another class, named
LoginBean
. The
Configurator
doesn't offer access to his List of Stages.

I cannot change the class
Configurator
.

My Idea:

Define a new bean called Stages and inject it to
Configurator
and
LoginBean
.
My problem with this idea is that I don't know how to transform this property:

<property ...>
<list>
<bean ... >...</bean>
<bean ... >...</bean>
<bean ... >...</bean>
</list>
</property>


into a bean.

Something like this does not work:

<bean id="stages" class="java.util.ArrayList">


Can anybody help me with this?

Answer

Import the spring util namespace. Then you can define a list bean as follows:

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


<util:list id="myList" value-type="java.lang.String">
    <value>foo</value>
    <value>bar</value>
</util:list>

The value-type is the generics type to be used, and is optional. You can also specify the list implementation class using the attribute list-class.

Comments