Dependency Injection in Java (with Example)
Dependency Injection (DI) is a design pattern used to achieve Inversion of Control (IoC) between
classes and their dependencies.
It allows for better modularization and makes code easier to manage and test.
Types of Dependency Injection:
1. Constructor Injection
2. Setter Injection
3. Field Injection
Example (Constructor Injection):
// Service Interface
public interface MessageService {
void sendMessage(String message, String receiver);
// Service Implementation
public class EmailService implements MessageService {
public void sendMessage(String message, String receiver) {
System.out.println("Email sent to " + receiver + " with message: " + message);
// Client Class
public class MyApplication {
private MessageService service;
// Constructor Injection
public MyApplication(MessageService service) {
this.service = service;
public void processMessage(String msg, String rec) {
service.sendMessage(msg, rec);
// Main Class to run the application
public class Main {
public static void main(String[] args) {
MessageService service = new EmailService(); // Dependency
MyApplication app = new MyApplication(service); // Injecting dependency
app.processMessage("Hello", "[email protected]");
Advantages of DI:
- Reduces coupling between components
- Improves code maintainability
- Enhances testability
Frameworks like Spring use DI extensively to manage bean lifecycles and dependencies.