Showing posts with label Constructor Injection. Show all posts
Showing posts with label Constructor Injection. Show all posts

Spring: Constructor Injection by Example

In our last tutorial we have seen about Setter Injection by simple example. In this tutorial we see same example with Constructor Injection. Only thing which we need to take care is "constructor-arg" order and type should match with bean class constructor method. Otherwise constructor injection argument type ambiguities exception will be thrown.
Dependency Injection with Spring


<project xmlns="" xmlns:xsi=""

  <!-- Spring Core -->


public class Employee {

 private String empName;
 private int age;
 private String gender;

 public Employee(String empName, int age, String gender){
  this.empName = empName;
  this.age = age;
  this.gender = gender;
 public String getEmpName() {
  return empName;
 public int getAge() {
  return age;
 public String getGender() {
  return gender;


public class Office {

 private String offName;
 private String offAddress;
 private Employee employee;
 public Office(String offName, String offAddress, Employee employee){
  this.offName = offName;
  this.offAddress = offAddress;
  this.employee = employee;
 public String getOffName() {
  return offName;
 public String getOffAddress() {
  return offAddress;
 public Employee getEmployee() {
  return employee;


<beans xmlns=""
    <bean id="emp" class="">
    <bean id="office" class="">
        <constructor-arg><value>ABCD Crop.</value></constructor-arg>
   <constructor-arg><value>Bangalore, India</value></constructor-arg>
   <constructor-arg ref="emp"></constructor-arg>


import org.springframework.context.ApplicationContext;
import org.springframework.context.ConfigurableApplicationContext;

public class TestClass {

 public static void main(String[] args) {
  ApplicationContext appCon = new ClassPathXmlApplicationContext("Spring-Core.xml");
  Office office = (Office)appCon.getBean("office");
  System.out.println("Office Name    : "+office.getOffName());
  System.out.println("Office Address : "+office.getOffAddress());
  System.out.println("Employee Name  : "+office.getEmployee().getEmpName());
  System.out.println("Employee Age   : "+office.getEmployee().getAge());
  System.out.println("Employee Gender: "+office.getEmployee().getGender());


Office Name    : ABCD Crop.
Office Address : Bangalore, India
Employee Name  : Steve
Employee Age   : 35
Employee Gender: Male
Spring: Constructor Injection by Example