Spring List Factory


 

Spring List Factory

In this tutorial you will learn about spring list factory and how list is used in spring framework.

In this tutorial you will learn about spring list factory and how list is used in spring framework.

Spring List Factory

Ths ListFactoryBean is a simple factory for shared List instance. The list element is defined in the xml bean definitions. The setSourceList method set the source List which is written in xml list element. The SetTargetListClass method set the class to use target List.

Week.java

package list.factory.example;

import java.util.List;

public class Week {
	private List days;

	public List getDays() {
		return days;
	}

	public void setDays(List days) {
		this.days = days;
	}

	@Override
	public String toString() {
		return "Days [lists=" + days + "]";

	}
}

AppMain.java

package list.factory.example;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class AppMain {
	public static void main(String[] args) {
		ApplicationContext context = new ClassPathXmlApplicationContext(
				new String[] { "context.xml" });
		Week weekday = (Week) context.getBean("week");
		System.out.println(weekday);
	}
}

context.xml

<?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:aop="http://www.springframework.org/schema/aop"
  xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

  <bean id="week" class="list.factory.example.Week">
    <property name="days">
      <bean class="org.springframework.beans.factory.config.ListFactoryBean">
        <property name="targetListClass">
          <value>java.util.ArrayList</value>
        </property>
        <property name="sourceList">
          <list>
            <value>Monday</value>
            <value>Tuesday</value>
            <value>Wednesday</value>
            <value>Thursday</value>
            <value>Friday</value>
            <value>Saturday</value>
            <value>Sunday</value>
          </list>
        </property>
      </bean>
    </property>
  </bean>

</beans>

When you run this application it will display message as shown below:


Days [lists=[Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday]]

Download this example code

Ads