Searching...
Thursday, 27 June 2013

Spring Injecting Collection Example

10:00

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

Example

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="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
   <bean id="Order" class="com.pretech.dependency.Order">
      <property name="orderNumber" value="1212" />
    <property name="orderItems">
    <list>
        <value>PEPSI</value>
        <value>COCA-COLA</value>
        <value>MIRINDA</value>
        <value>FANTA</value>
    </list>
</property>
    </bean>
</beans>
Note: Added List and its values

4. Create a Main program (OrderDetails.java)

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


    public static void main(String[] args) {
 
        ApplicationContext context = new ClassPathXmlApplicationContext(
                "OrderDetails.xml");
        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]

0 comments: