---
obj: concept
---
# Dependency Injection

## **Description:**
Dependency Injection (DI) is a design pattern used in software development to achieve Inversion of Control (IoC). It helps manage the dependencies between components or classes by externalizing the dependencies and injecting them rather than having the components create their own dependencies. This promotes loose coupling, testability, and flexibility in your code.

**How it's Used:**
1. **Dependency**: Identify the dependencies that a class or component needs to function properly. These dependencies can be other objects, services, or configurations.
2. **Injection Mechanism**: Create a mechanism to provide these dependencies to the class that needs them. This can be done in several ways, such as constructor injection, setter injection, or method injection.
3. **Injection Container (Optional)**: In larger applications, you may use an injection container or a framework (e.g., Spring, Guice) to manage and automatically inject dependencies. These containers can handle the creation and wiring of objects.
4. **Client Code**: In your application, create instances of the classes and inject the required dependencies. This can be done manually or by using an injection container.

## **Example:**
Consider a simple Java application where you have a `UserService` class that depends on a `UserRepository` to retrieve user data from a database. Here's how Dependency Injection can be applied:

- **Identify Dependencies**: Recognize that `UserService` depends on `UserRepository`.
- **Injection Mechanism**: Use constructor injection to inject the `UserRepository` dependency into the `UserService` class.

```java
public class UserService {
    private final UserRepository userRepository;

    public UserService(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    // Use userRepository to perform user-related operations
}
```

- **Client Code**: In your application code, create instances of `UserRepository` and `UserService`, and inject the `UserRepository` into the `UserService`.

```java
public class Main {
    public static void main(String[] args) {
        UserRepository userRepository = new UserRepository(); // or use an injection container
        UserService userService = new UserService(userRepository);

        // Use the userService to work with users
    }
}
```

By using Dependency Injection, you've decoupled the `UserService` and `UserRepository`, making it easier to replace or test these components independently. You can change the `UserRepository` implementation or switch to a mock repository for testing without modifying the `UserService` class. This promotes modularity and maintainability in your code.