View RSS Feed

Spring Framework

Dependency Injection in Spring

Rate this Entry
by , 07-07-2012 at 06:21 PM (781 Views)
A few working object makes a java application which is seen by the end user as a working application. The application classes must be independent and loosely coupled in case of complex and large Java applications from other Java classes in order to increase reusability chances. Also this approach makes the testing process easy in the unit testing of complex Java application. These classes are integrated together by the dependency injection also known as wiring and it also takes the same amount of time to keep them independent.
For example, your application contains the text editor component and you are interested in integrating spell checking. Following is the standard piece of code for your application.
Java Code:
public class MyTextEditor {
   private MySpellChecker mySpellChecker;
   public MyTextEditor() {
      mySpellChecker = new MySpellChecker();
   }
}
In the above code, a dependency between SpellChecker and TextEditor is created. For the control inversion, the above code can be written in following format.
Java Code:
public class MyTextEditor {
   private MySpellChecker mySpellChecker;
   public TextEditor(MySpellChecker mySpellChecker) {
      this.mySpellChecker = mySpellChecker;
   }
}
In the above code, the TextEditor is not worried about the implementation of the SpellChecker. It will be implemented independently and its object will be provided to TextEditor when the TextEditor is instantiated and the Spring framework will control this entire process.

Submit "Dependency Injection in Spring" to Facebook Submit "Dependency Injection in Spring" to Digg Submit "Dependency Injection in Spring" to del.icio.us Submit "Dependency Injection in Spring" to StumbleUpon Submit "Dependency Injection in Spring" to Google

Comments