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

In my last post we’ve seen how to setup our project to play with Spring and DI – Creating a simple Spring project. Today we’ll try to understand whole idea about DI backed by few examples.

To continue with our project lets create a package di.example.one under com.programmerscuriosity.springforblogdemo and define MessageService interface that includes one method, sendMessage(String subject, String message).

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

public interface MessageService {

void sendMessage(String subject, String message);
}

And then let’s create few classes that implement MessageService interface:

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

public class EmailService implements MessageService {

    @Override
    public void sendMessage(String subject, String message) {
        System.out.println("Mail: " + subject + " - " + message);
    }
}
package com.programmerscuriosity.springforblogdemo.di.example.one;

public class SmsService implements MessageService {

    @Override
    public void sendMessage(String subject, String message) {
        System.out.println("SMS: " + subject + " - " + message);
    }
}
package com.programmerscuriosity.springforblogdemo.di.example.one;

public class TweetService implements MessageService {

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

To try out the service let’s create a simple controller class:

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

@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";
    }
}

If you now run the application and visit http://localhost:8080/message, you should see “Very important e-mail was sent” and in the console you should see the standard print output lines:

Mail: Very important e-mail. – Please read this e-mail carefully.

One thought on “DI – let’s try to understand it – part 1”

Leave a Reply