tags:

views:

706

answers:

4

Hi!

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?

+3  A: 

Would this work for you?

<bean id="stage1" class="Stageclass"/>
<bean id="stage2" class="Stageclass"/>

<bean id="stages" class="java.util.ArrayList">
    <constructor-arg>
        <list>
            <ref bean="stage1" />
            <ref bean="stage2" />                
        </list>
    </constructor-arg>
</bean>
stacker
+1 - I didn't know you could do that (though I can see that it should work). Suggestion: I think you should be able to embed the `StageClass` bean declarations in the `<list>` avoiding the need for the `<ref>` elements.
Stephen C
A: 

import the spring util namespace then you can define a list bean like so:

<?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"&gt;


<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. Yuo can also specify the list impementatino class using the attribute 'list-class'

HTH

simonlord
and obviously the contents of the list can be values, references, and beans etc..
simonlord
+1  A: 

I think you may be looking for org.springframework.beans.factory.config.ListFactoryBean.

You declare a ListFactoryBean instance, providing the list to be instantiated as a property withe a <list> element as its value, and give the bean an id attribute. Then, each time you use the declared id as a ref or similar in some other bean declaration, a new copy of the list is instantiated. You can also specify the List class to be used.

Stephen C
It's a nice hint, but I don't get it working. stakker's anwer worked. +1 for the hint.
furtelwart
A: 

Use the util namespace, you will be able to register the list as a bean in your application context. You can then reuse the list to inject it in other bean definitions.

Juan Perez