The Spring Framework: Understanding IoC
In Spring, the Inversion of Control (IoC) principle is implemented using the Dependency Injection (DI) design pattern. IoC or Inversion of Control is one of the core features of Spring. It helps in simplifying the implementation of business logic. To use the Spring Framework to its full potential, understanding the IoC container of the framework is essential.
Let's understand dependency injection with the help of an example. First we will see a java version of the example and later we will add spring functionalities to it. As far as the example go, its pretty simple. The Quiz interface exposes the getQuestion() method. To keep things simple, our Quiz will generate only one question.
Quiz.java
----------------
package com.ideeksha;
public interface Quiz {
public String getQuestion();
}
The StrutsQuiz and the SpringQuiz class implements Quiz interface and they generate questions related to struts and spring respectively.
StrutsQuiz.java
----------------------
package com.ideeksha;
public class StrutsQuiz implements Quiz {
@Override
public String getQuestion() {
return "Are you new to Struts?";
}
}
SpringQuiz.java
----------------------
package com.ideeksha;
public class SpringQuiz implements Quiz {
@Override
public String getQuestion() {
return "Are you new to Spring?";
}
}
We have a QuizService class that displays the question to the user. The QuizService class holds reference to the Quiz.
QuizService.java
-----------------------
package com.ideeksha;
public class QuizService {
private Quiz quiz = new SpringQuiz ();
public void askQuestion()
{
System.out.println(quiz.getQuestion());
}
}
Finally we create the QuizProgram class to conduct quiz.
QuizProgram.java
----------------
package com.ideeksha;
public class QuizProgram {
public static void main(String[] args) {
QuizService quizService = new QuizService();
quizService.askQuestion();
}
}
As you can see it is pretty simple, here we create an instance of the QuizService class and call the askQuestion() method. When you run the program as expected "Are you new to Spring?" gets printed in the console.
Spring Dependency Injection
Let's have a look at the class diagram of this example. The green arrows indicate generalization and the blue arrows indicates association.
As you can see this architecture is tightly coupled. We create an instance of the Quiz in the QuizService class in the following way.
private Quiz quiz = new SpringQuiz();
To make our quiz master Struts genius we need to make modifications to the QuizService class like this.
private Quiz quiz = new StrutsQuiz();
So it is tightly coupled. Now lets see how we can avoid this by using the Dependency Injection design pattern. The Spring framework provides prowerful container to manage the components. The container is based on the Inversion of Control (IoC) principle and can be implemented by using the Dependency Injection (DI) design pattern. Here the component only needs to choose a way to accept the resources and the container will deliver the resource to the components.
In this example instead of we, directly creating an object of the Quiz bean in the QuizService class, we make use of the container to do this job for us. Instead of hard coding any values we will allow the container to inject the required dependancies.
We can inject the dependancies using the setter or constructor injection. Here we will see how we can do this using the setter injection.
QuizService.java
-----------------------
package com.ideeksha;
public class QuizService {
Quiz quiz;
public void setQuiz(Quiz quiz) {
this.quiz = quiz;
}
public void askQuestion()
{
System.out.println(quiz.getQuestion());
}
}
The value for the Quiz will be set using the setQuiz () method. The Quiz object is never instantiated in the QuizService 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.
After making all the changes, the class diagram of the example look like this.
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="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.xsd">
<bean id="springQuiz" class="com.ideeksha.SpringQuiz"></bean>
<bean id="strutsQuiz" class="com.ideeksha.StrutsQuiz"></bean>
<bean id="quizService" class="com.ideeksha.QuizService">
<property name="quiz">
<ref local="springQuiz"/>
</property>
</bean>
</beans>
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 SpringQuiz is injected to the Quiz bean. When we execute this example, "Are you new to Spring?" gets printed in the console.
To make our Quiz ask questions related to Struts, the only change we need to do is, to change the bean reference in the ref tag.
<bean id="quizService" class="com.ideeksha.QuizService">
<property name="quiz">
<ref local="strutsQuiz"/>
</property>
</bean>
In this way the Dependency Injection helps in reducing the coupling between the components. And yes it says “NO” to ‘new’ operator!!!
To Run This example
QuizExample.java
---------------------------
package com.ideeksha;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class QuizProgram {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
QuizService quizService = (QuizService) context.getBean("quizService");
quizService.askQuestion();
}
}
More things on Spring IOC --Ways to do Spring dependency Injection !!!
Inversion of Control or IoC is one of the techniques used to wire services or components to an application program. By definition, IoC is “A software design pattern and set of associated programming techniques in which the flow of control of a system is inverted in comparison to the traditional interaction mode.” Simply stated, in IoC, instead of an application calling the framework, it is the framework that calls the components specified by the application.
This approach is similar to the one that Hollywood agents adopt with their clients. It is sometimes known as “Don’t call me, I will call you.” This is why IoC is also known as the Hollywood approach.
However, IoC is a broad and generic term. The aspect of IoC that the Spring Framework uses is "Injection of required resources or dependency at Run-time into the dependent resource," which is also known as Dependency Injection. Hence, the service provided by the IoC container of Spring is Dependency Injection. Therefore, I will be using the terms IoC and Dependency Injection in a lax way.
There are three forms or styles of Dependency Injection. They are:
1. Constructor Injection
2. Setter Injection
3. Interface Injection
Of these, the Spring Framework directly supports the first and second forms whereas the third form is supported indirectly. Between the first and the second, the Spring Framework prefers the use of second rather than the first. Here are the details.
1. Constructor Injection: In Constructor Injection, an IoC container uses the constructor to inject the dependency. All the dependencies, whether they are simple values or references to other objects, are declared in the constructor. One of the advantages of Constructor Injection is that all the dependencies are declared in one go. This also helps in understanding whether the class depends on too many services.
2. Setter Injection: This form of Dependency Injection uses Setters, also known as mutators (because they change the value of the corresponding instance variables), to inject the required resources or dependencies. In other words, each of the objects that the class depends upon will have a setter and the IoC container will use the setters to provide the resource at run-time.
The main difference between Constructor Injection and Setter Injection is that in Constructor Injection, the handing over of the dependencies takes place during instantiation of the dependent object, whereas with Setter Injection, it takes place after the dependent object is instantiated. The Spring Framework favors Setter Injection over Constructor Injection.
3. Interface Injection: Interface Injection provides the concrete implementations of an interface to the dependent object according to the configuration. The main difference between Interface Injection and the previous two is that in Interface Injection, any of the implementations of the interface can be injected, whereas with the other two, the object of the class specified is injected. Spring does not provide direct support for Interface Injection.
That completes the overview of IoC.
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.context.support-3.0.0.M3
org.springframework.core-3.0.0.M3
org.springframework.expression-3.0.0.M3
2 comments :
This was a useful page.It resolved many of my queries.Good work Anil.
Good Work....
Keep it up.
Post a Comment