Saturday 16 April 2016

Dependency Injection for Objects in Spring


Now as we already know how to push up properties in to bean using Spring DI, its now a time to take a next step towards containment using Spring. 

In many real life scenario we need to have the object as a property of bean. For instance, if we are creating Employee object like : 


public class Employee {
int empId;
String empName;
Date dt_of_join;

public int getEmpId() {
return empId;
}

public void setEmpId(int empId) {
this.empId = empId;
}

public String getEmpName() {
return empName;
}

public void setEmpName(String empName) {
this.empName = empName;
}

public Date getDt_of_join() {
return dt_of_join;
}

public void setDt_of_join(Date dt_of_join) {
this.dt_of_join = dt_of_join;
}

}

Here the Employee is dependent on the object of Date. We need to create the object of Date and then insert it into Employee.

public class Date {
     int dd, mm, yy;

     public int getDd() {
          return dd;
     }

     public void setDd(int dd) {
          this.dd = dd;
     }

     public int getMm() {
          return mm;
     }

     public void setMm(int mm) {
          this.mm = mm;
     }

     public int getYy() {
          return yy;
     }

     public void setYy(int yy) {
          this.yy = yy;
     }

}

To achieve this containment concept , spring uses Dependency Injection using bean reference. We can do it by following change in our configuration file 


<beans>
<bean id="id1" class="Date">

<property name="dd" value="10" />
<property name="mm" value="12" />
<property name="yy" value="1982" />

</bean>

<bean id="id2" class="Employee">
<property name="empId" value="10" />
<property name="empName" value="Ajay" />
<property name="dt_of_join" ref="id1" />

</bean>


</beans>

We need to first of create a bean of Date class (id1) which we can inject in Employee bean (id2) by using attribute ref="id1" of property "dt_of_join". 

So one can add any number of beans of Date in xml file and can change the reference of that bean in Employee's property at run time without changing coding of application class/Employee class. 

One more important thing is even though we change the definition of Date class, the Employee class and Main application class file would remain unchanged. :-) 










No comments:

Post a Comment

Attend Online Java Certification Training and excel your career

Hello Java Developer,  Are you staying at home and worried about your future? Do not waste the time in worrying. International certifi...