Spring IoC
In Spring, the Inversion of Control (IoC) principle is implemented using the Dependency Injection (DI) design pattern. 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 QuizMater interface exposes the popQuestion() method. To keep things simple, our QuizMaster will generate only one question.
1.
QuizMaster.java
2.
----------------
3.
package
com.vaannila;
4.
5.
public
interface
QuizMaster {
6.
7.
public
String popQuestion();
8.
}
The StrutsQuizMaster and the SpringQuizMaster class implements QuizMaster interface and they generate questions related to struts and spring respectively.
01.
StrutsQuizMaster.java
02.
----------------------
03.
package
com.vaannila;
04.
05.
public
class
StrutsQuizMaster
implements
QuizMaster {
06.
07.
@Override
08.
public
String popQuestion() {
09.
return
"Are you new to Struts?"
;
10.
}
11.
12.
}
01.
SpringQuizMaster.java
02.
----------------------
03.
package
com.vaannila;
04.
05.
public
class
SpringQuizMaster
implements
QuizMaster {
06.
07.
@Override
08.
public
String popQuestion() {
09.
return
"Are you new to Spring?"
;
10.
}
11.
12.
}
We have a QuizMasterService class that displays the question to the user. TheQuizMasterService class holds reference to the QuizMaster.
01.
QuizMasterService.java
02.
-----------------------
03.
package
com.vaannila;
04.
05.
public
class
QuizMasterService {
06.
07.
private
QuizMaster quizMaster =
new
SpringQuizMaster();
08.
09.
public
void
askQuestion()
10.
{
11.
System.out.println(quizMaster.popQuestion());
12.
}
13.
}
Finally we create the QuizProgram class to conduct quiz.
01.
QuizProgram.java
02.
----------------
03.
package
com.vaannila;
04.
05.
public
class
QuizProgram {
06.
07.
public
static
void
main(String[] args) {
08.
QuizMasterService quizMasterService =
new
QuizMasterService();
09.
quizMasterService.askQuestion();
10.
}
11.
12.
}
As you can see it is pretty simple, here we create an instance of the QuizMasterService class and call the askQuestion() method. When you run the program as expected "Are you new to Spring?" gets printed in the console.
Comments
Post a Comment