tl  tr
  Home | Tutorials | Articles | Videos | Products | Tools | Search
Interviews | Open Source | Tag Cloud | Follow Us | Bookmark | Contact   
 Spring > Core > List Setter Injection

List Setter Injection 

Spring Inversion of Control (IoC) also known as Dependency Injection (DI) is a process by which objects define their dependencies with collaborating objects. Setter-based dependency injection allows us to inject dependencies through setter methods. This example shows injecting employee list.

File Name  :  
/SpringCore001/conf/setter/list_setter_inj.xml 

File Name  :  
com/bethecoder/tutorials/spring3/basic/Employee.java 
   
package com.bethecoder.tutorials.spring3.basic;

public class Employee {
  
  private int id;
  private String name;
  private double salary;
  
  public Employee() {
    super();
    this.id = -1;
    this.name = "Unknown";
    this.salary = 0;
  }
  
  public Employee(int id, String name) {
    super();
    this.id = id;
    this.name = name;
    this.salary = 20000;
  }
  
  public Employee(int id, String name, double salary) {
    super();
    this.id = id;
    this.name = name;
    this.salary = salary;
  }

  public int getId() {
    return id;
  }
  
  public void setId(int id) {
    this.id = id;
  }
  
  public String getName() {
    return name;
  }
  
  public void setName(String name) {
    this.name = name;
  }
  
  public double getSalary() {
    return salary;
  }
  
  public void setSalary(double salary) {
    this.salary = salary;
  }
  
  public String toString() {
    return "Employee[" + id + ", " + name + ", " + salary + "]";
  }
  
}
   

File Name  :  
com/bethecoder/tutorials/spring3/basic/Department.java 
   
package com.bethecoder.tutorials.spring3.basic;

import java.util.List;

public class Department {

  private Employee manager = null;
  private List<Employee> employees = null;

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

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

  public Employee getManager() {
    return manager;
  }

  public void setManager(Employee manager) {
    this.manager = manager;
  }
  
}
   

File Name  :  
com/bethecoder/tutorials/spring3/tests/setter/ListSetterInjection.java 
Author  :  Sudhakar KV
Email  :  [email protected]
   
package com.bethecoder.tutorials.spring3.tests.setter;

import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;

import com.bethecoder.tutorials.spring3.basic.Department;

public class ListSetterInjection {

  /**
   @param args
   */
  public static void main(String[] args) {
    XmlBeanFactory factory = new XmlBeanFactory(
                new ClassPathResource("list_setter_inj.xml"));

    Department dept = (Departmentfactory.getBean("dept");
    System.out.println(dept.getEmployees());

  }

}
   

It gives the following output,
[Employee[1, ABC, 90000.0], Employee[2, XYZ, 60000.0]]



 
  


  
bl  br