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.

package com.programmerscuriosity.springforblogdemo.controllers;

@RestController
public class MessageController {

    private MessageService messageService = new EmailService();

    @RequestMapping("/message")
    public String sendMessage() {
        messageService.sendMessage("Very important e-mail.", "Please read this e-mail carefully.");
        return "Very important e-mail was sent";
    }
}

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.

package com.programmerscuriosity.springforblogdemo.di.example.two;

@Component
public class TweetService implements MessageService {

    @Override
    public void sendMessage(String subject, String message) {
        System.out.println("Tweet: " + subject + " - " + message);
    }
}

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

package com.programmerscuriosity.springforblogdemo.controllers;

@RestController
public class MessageController {

    @Resource
    private MessageService messageService;

    @RequestMapping("/message")
    public String sendMessage() {
        messageService.sendMessage("Very important:", "Please read this carefully.");
        return "Your message was sent";
    }
}

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

“Your message was sent”

and

Tweet: Very important: – Please read this carefully.

as a output in console.

 

Leave a Reply