P Name Space Reference
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 P Name space reference which allows us to
use the bean element's attributes, instead of nested property elements.
01
<?
xml
version
=
"1.0"
encoding
=
"UTF-8"
?>
08
<
bean
id
=
"dept"
class
=
"com.bethecoder.tutorials.spring3.basic.Department"
>
09
<
property
name
=
"manager"
ref
=
"emp1"
/>
12
<
bean
id
=
"dept2"
class
=
"com.bethecoder.tutorials.spring3.basic.Department"
16
<
bean
id
=
"emp1"
class
=
"com.bethecoder.tutorials.spring3.basic.Employee"
>
17
<
property
name
=
"id"
value
=
"1"
/>
18
<
property
name
=
"name"
value
=
"ABC"
/>
19
<
property
name
=
"salary"
value
=
"90000"
/>
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.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;
}
}
package com.bethecoder.tutorials.spring3.tests.pnamespace;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
import com.bethecoder.tutorials.spring3.basic.Department;
public class ReferenceTests {
/**
* @param args
*/
public static void main ( String [] args ) {
XmlBeanFactory factory = new XmlBeanFactory (
new ClassPathResource ( "pns_reference.xml" )) ;
Department dept = ( Department ) factory.getBean ( "dept" ) ;
System.out.println ( dept.getManager ()) ;
Department dept2 = ( Department ) factory.getBean ( "dept2" ) ;
System.out.println ( dept2.getManager ()) ;
}
}
It gives the following output,
Employee[1, ABC, 90000.0]
Employee[1, ABC, 90000.0]