Monday, 20 May 2013

Spring Dependency Injection using Constructor - Spring IoC

Spring IoC – Dependencies injection Examples

Welcome to second part of Spring Dependency Injection tutorial series, in previous article we came across a quick introduction about Spring IOC and Spring DI. In this particular blog we will see Spring IoC via Constructor method in details.

Constructor Injection Examples in Spring

Constructor injection is second approach to implement Depenendency injection in Spring. Constructor-based DI is accomplished when the container invokes a class constructor with a number of arguments, each representing a dependency on other class.

Situation

The scenario is that we have two classes, StudentImpl and StudentPhoneNumberImpl , each class is implementing an interface Student and StudentPhoneNumber respectively.

StudentPhoneNumberImpl.java – Class

StudentPhoneNumberImpl class is a simple class, to call any of its method we need to create an hard coded object of this class. But in this blog we will call it's methods using a reference of StudentPhoneNumber interface.

Objective

Our objective is to call ‘getStudentPhone()’ method of StudentPhoneNumberImpl class in StudentImpl class without creating a dependency in between these two classes. This can be done using constructor injection method of spring ioc.

Solution

We need to do two things here :

1) Register the two classes as beans in servlet-context and define their relation. See the configuration:

First of all we have defined two classes here as a bean, and than we have injected a property named studentPhone as a property of StudentImpl class. Now this property studentPhone will be used as an object of ‘StudentPhoneImpl’ class inside StudentImpl Class.

2) Define ‘studentPhone’ property in StudentImpl class and make an pass an object of StudentPhoneNumber in constructor of StudentImpl.

In this particular blog we came accross a quick introduction to Spring DI and Spring IOC using Constructor Injection method. In next and final part of the series of Spring IOC tutorial we will cover Spring DI via Setter Method.