Example of simple DI

NotifictionService represents a common service interface for sending data to a different system:

public interface NotificationService {
boolean sendNotification(String message, String recipient);
}

The previous interface defines a method signature for sendNotification() by passing the message and recipient details and returning the type as Boolean. SMSService.java is a concrete implementation of this interface for sending SMS notifications:

public class SMSService implements NotificationService {

public boolean sendNotification(String message, String recipient) {
// Code for sending SMS
System.out.println("SMS message has been sent to " + recipient);
return true;
}
}

The previous class implemented code for sending SMS by accepting the message and recipient details. Now, we create a client application, NotificationClient.java, which will use NotificationService to initialize the actual SMSService. The same object can be used to send notifications to different systems, including email or custom notifications:

public class NotificationClient {

public static void main(String[] args) {
NotificationService notificationService = new SMSService();
notificationService.sendNotification("Hello", "1234567890");
}

}

In the previous example, even though implementation and interface are loosely coupled, we need to create a manual instance of the real implementation of the class in the client application. In this scenario, at compilation time, the client application knows which execution classes related to interfaces will be bound.

That is the thing that Google Guice does; it takes instances as services from the client application code and the dependency between the clients, and their service is consequently injected through a simple configuration mechanism.

Let's see an example of dependency injection in Guice by using different API in the next topic.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.219.249.210