0% found this document useful (0 votes)
6 views

Dependency_Injection_Java_Example

Dependency Injection (DI) is a design pattern that promotes Inversion of Control (IoC) to improve modularization, manageability, and testability of code. There are three types of DI: Constructor Injection, Setter Injection, and Field Injection, with an example provided using Constructor Injection. DI reduces coupling, enhances maintainability, and is widely used in frameworks like Spring for managing dependencies.

Uploaded by

Aditya Rajput
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

Dependency_Injection_Java_Example

Dependency Injection (DI) is a design pattern that promotes Inversion of Control (IoC) to improve modularization, manageability, and testability of code. There are three types of DI: Constructor Injection, Setter Injection, and Field Injection, with an example provided using Constructor Injection. DI reduces coupling, enhances maintainability, and is widely used in frameworks like Spring for managing dependencies.

Uploaded by

Aditya Rajput
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 3

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.

You might also like