Dependency Injection Example

Let’s suppose there is a class NotificationService

package com.sks;

import java.util.List;

public class NotificationService {
	
	private EmailService service = new EmailService();
	
	public void notifyUser() {
		service.sendNotification();
	}

}

EmailService.java

package com.sks;


public class EmailService {

	@Override
	public void sendNotification() {
		System.out.println("User notified by email!");
		
	}

}

Test Class

package com.sks;

import java.util.ArrayList;
import java.util.List;

public class NotificationTest {
	
	public static void main(String[] args) {
		
		NotificationService ntfnService = new NotificationService();
		
		ntfnService.notifyUser();
		
	}
}

Now, let’s assume tomorrow, we don’t want to send email notification, rather we want to send the SMS notification. In that case, we need to change our code of NotificationService. It needs to have SMSService as dependency. It is tight coupling.
Let’s see the dependency injection from outside examples now.

Introduce an interface Notification

package com.sks;

@FunctionalInterface
public interface Notification {
	
	void sendNotification();

}

Modified EmailService

package com.sks;

//EmailService is-A Notification type
public class EmailService implements Notification {

	@Override
	public void sendNotification() {
		System.out.println("User notified by email!");
		
	}

}

SMSService

package com.sks;

//SMSService is-A Notification type
public class SMSService implements Notification {
	
	@Override
	public void sendNotification() {
		System.out.println("User notified by sms");
		
	}

}

NotificationService

package com.sks;

import java.util.List;

public class NotificationService {
	
	//Keep a reference of Notification
	private List<Notification> notifications;
	
	public NotificationService(List<Notification> notifications) {
		super();
		this.notifications = notifications;
	}

	public void notifyUser() {
		notifications.forEach(n -> n.sendNotification());
	}

}

Test Class

package com.sks;

import java.util.ArrayList;
import java.util.List;

public class NotificationTest {
	
	public static void main(String[] args) {
		
		List<Notification> notifications = new ArrayList<>();
		//notifications.add(new SMSService());
		notifications.add(new EmailService());
		
		NotificationService ntfnService = new NotificationService(notifications);
		
		ntfnService.notifyUser();
		
	}
}

In Inversion of control, this dependency injection is done by spring framework.