Dec 23, 2012

Spring Framework - Injecting a list

The example below demonstrates a Company bean class with two properties namely company name and the employees list. Both these properties are injected by the spring container.

<?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.xsd">
 <bean id="myCompany" class="com.examples.spring.Company">
     <property name="name" value="myWorld"/>
  <property name="employees">
      <list>
          <bean class="com.examples.spring.Employee">
              <constructor-arg name="name" value="Pankaj Tiwari" />
          </bean>
          <bean class="com.examples.spring.Employee">
              <constructor-arg name="name" value="Paresh Tiwari" />
          </bean>
          <bean class="com.examples.spring.Employee">
              <constructor-arg name="name" value="Ankit Rawat" />
          </bean>
      </list>
  </property>
 </bean>
</beans>

Shown above is the spring's bean definition file. Make sure that the Company class has a setter method setEmployees as shown below

package com.examples.spring;

import java.util.List;

public class Company {
 private String companyName;
 private List<Employee> employees;

 public void setName(String name) {
  this.companyName = name;
 }

 public String getName() {
  return companyName;
 }

 public void setEmployees(List<Employee> employees) {
  this.employees = employees;
 }

 public List<Employee> getEmployees() {
  return employees;
 }
}

The Employee is a simple bean whose name property we are setting through the constructor injection
package com.examples.spring;

public class Employee {
 private String empName;

 public Employee(String name) {
  this.empName = name;
 }

 public String getName() {
  return empName;
 }
}

The Application Tester program. For keeping the example simple, I am just verifying the number of employees in the list.
package com.examples.spring;

import junit.framework.Assert;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * File: AppTest.java
 */
public class AppTest {

 ApplicationContext ctx = null;

 @Before
 public void setup() {
  ctx = new ClassPathXmlApplicationContext("beans.xml");
 }

 @After
 public void cleanup() {
 }

 @Test
 public void testPropertyInjection() {
  Company myCompany = (Company) ctx.getBean("myCompany");
  Assert.assertEquals(myCompany.getName(), "myWorld");
  Assert.assertTrue(myCompany.getEmployees().size() == 3);
 }
}

No comments :

Post a Comment