Friday, March 18, 2011

Reducing coupling by IOC of Spring Example

We have already seen, traditional way of holding the quizmaster here - Tight coupling in application without spring.
The value for the QuizMaster will be set using the setQuizMaster() method. The QuizMaster object is never instantiated in the QuizMasterService class, but still we access it. Usually this will throw a NullPointerException, but here the container will instantiate the object for us, so it works fine.
Now consider this service, which refer these beans, but have now nothing to worry about how to create beans :

public class QuizMasterService {

   QuizMaster quizMaster;
   public void setQuizMaster(QuizMaster quizMaster) {
       this.quizMaster = quizMaster;
    public void askQuestion()

After making all the changes, the class diagram of the example look like this.
dependency injection reduction spring

 The container comes into picture and it helps in injecting the dependancies.
The bean configuration is done in the beans.xml file.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns=""
    <bean id="springQuizMaster" class="com.vaani.spring.quizmaster.SpringQuizMaster"></bean>
    <bean id="strutsQuizMaster" class="com.vaani.spring.quizmaster.StrutsQuizMaster"></bean>
    <bean id="quizMasterService" class="com.vaani.spring.quizmaster.QuizMasterService">
        <property name="quizMaster">
        <ref local="springQuizMaster"/>
We define each bean using the bean tag. The id attribute of the bean tag gives a logical name to the bean and the class attribute represents the actual bean class. The property tag is used to refer the property of the bean. To inject a bean using the setter injection you need to use the ref tag.
Here a reference of SpringQuizMaster is injected to the QuizMaster bean. When we execute this example, "Are you new to Spring?" gets printed in the console.
To make our QuizMaster ask questions related to Struts, the only change we need to do is, to change the bean reference in the ref tag.
<bean id="quizMasterService" class="com.vaani.spring.quizmaster.QuizMasterService">
   <property name="quizMaster">
       <ref local="strutsQuizMaster"/>
In this way the Dependency Injection helps in reducing the coupling between the components.
To execute this example add the following jar files to the classpath.

  • antlr-runtime-3.0
  • commons-logging-1.0.4
  • org.springframework.asm-3.0.0.M3
  • org.springframework.beans-3.0.0.M3
  • org.springframework.context-3.0.0.M3
  • org.springframework.core-3.0.0.M3
  • org.springframework.expression-3.0.0.M3

No comments:

Post a Comment