Posted by: shabrinath | June 23, 2009

Dependency Injections in Spring

Dependency Injection (Inversion of Control in Spring)

Java components/classes should be as independent as possible of other java classes. This increases the possibility to re-use these classes and test them independently of other classes.  To decouple Java components from other Java components, the dependency to a certain/other class should get injected into them rather that the class itself creates / finds this object.  The general concept behind dependency injection is called Inversion of Control.  A class should not configure itself but should be configured from outside.  Spring just adds some simplifications in using dependency injection by providing a standard way of providing the configuration and by managing the reference to the created objects.  The fundamental functionality provided by spring container is dependency injection.  The container allows to inject required objects to other objects.  This results in a loosely coupled design.  Dependency injection in spring is done via setter injection or via constructor injection.

Constructor Versus Setter Injection in Spring

The primary advantage of injection by itself, is that it requires very simple conventions. You don’t have to do anything special in your component and can leave the injector to take over and get stuff done for you.

Dependency Injection via Constructor Arguments:

Constructors with valid arguments gives you a clear statement as of what it means by  creating a valid object at an obvious place. If there are multiple ways to do it, create multiple constructors that gives the different possible combination by which an object needs to be created.  Another advantage with constructor initialization is that it allows to hide any fields which are immutable by simply not providing a setter.  If something should not change, the lack of a setter communicates this very well.

Spring generally advocates the usage of setter-based dependency injection as a large number of constructor arguments can get unwieldy especially when some properties are optional.   Beans defined in the bean factory that uses setter based injection are true java beans.


Leave a response

Your response:

Categories