Sunday, February 20, 2011

Spring DI

Java components / classes should be as independent as possible of other Java classes. This increases the possibility to reuse these classes and to test them independently of other classes(Unit Testing).
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.
A class A has a dependency to class B if class uses class B as a variable.
If dependency injection is used then the class B is given to class A via
  • the constructor of the class A - this is then called construction injection
  • a setter - this is then called setter injection
The general concept between dependency injection is called Inversion of Control.
A class should not configure itself but should be configured from outside.
A design based on independent classes / components increases the re-usability and possibility to test the software. For example if a class A expects a Dao (Data Access object) for receiving the data from a database you can easily create another test object which mocks the database connection and
inject this object into A to test A without having an actual database connection.
A software design based on dependency injection is possible with standard Java.
Spring just add some simplifications in using dependency injection by providing a standard way
of providing the configuration and by managing the reference to the created objects.

example of DI u can try it out:-
A helper class with a setter method.
package com.amit.output;
 
import com.amit.output.IOutputGenerator;
 
public class OutputHelper
{
 IOutputGenerator outputGenerator;
 
 public void setOutputGenerator(IOutputGenerator outputGenerator){
  this.outputGenerator = outputGenerator;
 }
 
}
A bean configuration file to declare the beans and set the dependency 
via setter injection (property tag).
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
 
 <bean id="OutputHelper" class="com.amit.output.OutputHelper">
  <property name="outputGenerator">
   <ref bean="CsvOutputGenerator" />
  </property>
 </bean>
 
<bean id="CsvOutputGenerator" class="com.amit.output.impl.
CsvOutputGenerator" />
<bean id="JsonOutputGenerator" class="com.amit.output.impl.
JsonOutputGenerator" />
 
</beans>
 that is output generator is out put generator gernal class that is injected by
 any input generator dependancy.....
                                    @amit rawat








1 comment:

  1. Good article on web services, could you please let me know the process to figure out missing parameter in SOAP requests?

    ReplyDelete