Thursday, 27 June 2013

Spring Injecting Collection Example


Spring Injecting Collection

Spring framework facilitates to configure primitive data type using value attribute and object reference using ref attribute of the <property> tag. Both the cases it is dealing with passing singular value to bean. But Spring provides the option to pass the plural values like Java Collection types List, Set, Mat etc.
Here is one example to pass List of items to the bean from the configuration xml file


1. Create Order. java

package com.pretech.dependency;
import java.util.ArrayList;
public class Order {
    private String orderNumber;
    private ArrayList orderItems;
    public ArrayList getOrderItems() {
        return orderItems;
    public void setOrderItems(ArrayList orderItems) {
        this.orderItems = orderItems;
    public String getOrderNumber() {
        return orderNumber;
    public void setOrderNumber(String orderNumber) {
        this.orderNumber = orderNumber;

2. Create spring configuration file (OrderDetails.xml)

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="" xmlns:xsi="" xsi:schemaLocation="">
   <bean id="Order" class="com.pretech.dependency.Order">
      <property name="orderNumber" value="1212" />
    <property name="orderItems">
Note: Added List and its values

4. Create a Main program (

package com.pretech.dependency;
import org.springframework.context.ApplicationContext;
public class OrderDetails {
     * @param args

    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext(
        Order order = (Order) context.getBean("Order");
        System.out.println("Order item details "+order.getOrderNumber()""+order.getOrderItems());

5. Output

Order item details 1212  [PEPSI, COCA-COLA, MIRINDA, FANTA]