DI – let’s try to understand it – part 2

To continue our series about DI let’s look at our example of MessageController from previous post – DI – part 1.

Unfortunately there is a problem with our solution.

The MessageController class is dependent, has a tight dependency on the EmailService class. There is a hard connection between these two classes. That means, if we ever change our mind to use TweetService or SmsServce instead of EmailService, we’ll need to change the code this way:

private MessageService messageService = EmailServiceTweetService();

But this solution is no different from previous one. We still have both classes tightly coupled. And this is the time when DI comes handy.

First, we need to annotate TweetService class with Spring @Component annotation to tell Spring to keep instance of TweetService in Application Context, it is a place where Spring keeps objects (called Beans) instantiated.

And instantiating Our TweetService using @Resource annotation when Spring application start.

Running our application and typing http://localhost:8080/message in web browser address bar, we should see:

“Your message was sent”


Tweet: Very important: – Please read this carefully.

as a output in console.


Leave a Reply