RandomQuestion
RandomQuestion

Reputation: 6988

Inject values in list property dynamically in spring

In spring, I want to inject values in list property dynamically. Is it possible?

For e.g. Instead of specifying value 1 three times, does there exist some property which can repeat this values multiple times based on some value.

<bean id='myBean' class-"com.foo.Xyz">
 <property name="myList">
    <value>1</value>
    <value>1</value>
    <value>1</value>
 </property>
</bean>

Please let me know if question is not clear.

Upvotes: 0

Views: 1886

Answers (1)

Tomasz Nurkiewicz
Tomasz Nurkiewicz

Reputation: 340713

What about custom FactoryBean?

public class RepeatingListFactoryBean implements FactoryBean<Object> {

    private final Object item;
    private final int count;

    public RepeatingListFactoryBean(Object item, int count) {
        this.item = item;
        this.count = count;
    }

    @Override
    public Object getObject() throws Exception
    {
        final ArrayList<Object> list = new ArrayList<Object>(count);
        for(int i = 0; i < count; ++i)
            list.add(item);
        return list;
    }

    @Override
    public Class<?> getObjectType() {
        return item.getClass();
    }

    @Override
    public boolean isSingleton() {
        return true;
    }
}

You can use it in the following way (however I haven't tested it):

<bean id="listFactory" class="RepeatingListFactoryBean">
  <constructor-arg value="1"/>  <!-- item -->
  <constructor-arg value="3"/>  <!-- count -->
</bean>

<bean id="myBean" class-"com.foo.Xyz">
  <property name="myList" ref="listFactory"/>
</bean>

Note that both count and an object that is to be repeated are declaratively configurable.

Upvotes: 2

Related Questions