Dynamic list injection in Spring

Imagine you have a Spring XML configuration which defines a bean with a list property.
The bean could look like

public class MyBean {
	private List listProp;

	public void setListProp(List values) {
		this.listProp = values;
	}
}

Here is the spring config that defines the bean with a static list of values for the listProp property.

<bean id="myBean" class="de.mypackage.MyBean">
	<property name="listProp">
		<list>
			<value>a</value>
			<value>b</value>
			<value>c</value>
		</list>
	</property>
</bean>

If you don’t want to define a static list in the XML config, you could dynamically fill in the values using Java code and the Spring Expression Language.
In the following example, the method getListValues() of the class MyClass is used to retrieve the values for the list property of the bean.

<bean id="myBean" class="de.mypackage.MyBean">
	<property name="listProp" value="#{T(de.mypackage.MyClass).getListValues()}"/>
</bean>
Short URL for this post: http://wp.me/p4nxik-D2
This entry was posted in Spring Universe and tagged , , . Bookmark the permalink.

Leave a Reply