Bean Alias
Spring Inversion of Control (IoC ) also known as
Dependency Injection (DI ) is a process by which
objects define their dependencies with collaborating objects.
The following example shows using bean alias.
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 + "]" ;
}
}
package com.bethecoder.tutorials.spring3.tests.alias;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
import com.bethecoder.tutorials.spring3.basic.Employee;
public class BeanAlias {
/**
* @param args
*/
public static void main ( String [] args ) {
XmlBeanFactory factory = new XmlBeanFactory (
new ClassPathResource ( "bean_alias.xml" )) ;
Employee emp1 = ( Employee ) factory.getBean ( "emp1" ) ;
System.out.println ( "emp1 : " + emp1 ) ;
emp1 = ( Employee ) factory.getBean ( "firstEmployee" ) ;
System.out.println ( "firstEmployee : " + emp1 ) ;
emp1 = ( Employee ) factory.getBean ( "emp2_manager" ) ;
System.out.println ( "emp2_manager : " + emp1 ) ;
emp1 = ( Employee ) factory.getBean ( "emp4_colleague" ) ;
System.out.println ( "emp4_colleague : " + emp1 ) ;
emp1 = ( Employee ) factory.getBean ( "emp6_subordinate" ) ;
System.out.println ( "emp6_subordinate : " + emp1 ) ;
}
}
It gives the following output,
emp1 : Employee[1, XYZ, 80000.0]
firstEmployee : Employee[1, XYZ, 80000.0]
emp2_manager : Employee[1, XYZ, 80000.0]
emp4_colleague : Employee[1, XYZ, 80000.0]
emp6_subordinate : Employee[1, XYZ, 80000.0]