Learn with best explanation

Coding tutorials and solutions

Dependency Injection in Spring

Today in this tutorial we will learn and discuss very important concept of spring core which is commonly asked in interview is dependency injection (DI). Dependency injection is one of the fundamentals and playing main role when developing applications using spring framework.

What is (DI) Dependency Injection?

Dependency Injection is software design principle which is used to provide dependencies to the dependent objects or it is a design principle in which an object receives another object on which it depends. You might not get clear from the above definition, to under well we take an example of Employee object. Suppose Employee object has properties like name and email along with them it has another property of address object as in the following code snippet.

public class Employee {
    private String name;
    private String email;
    private Address address;
}

The address object has properties house no, street, city, state and country as in the following code snippet.

public class Address {
    private String houseNo;
    private String street;
    private String state;
    private String country;
}

Now for using Employee object properly we have to first create Address object because Employee object is relying on Address object. So, dependency injection is process of providing or creating instances of classes or objects for other classes or objects. No, I expect that you have understood the DI and I brief you the next concept.

Inversion of Control (IOC)

As we have already discussed Inversion of Control in details however we will brief it here. IoC is also software principle but in spring Dependency Injection is based on it. When using IoC actually we are passing control of creating instances for dependent class to container we as developer do not need to take care of suppling instances to the dependent objects container does this job for us.

Inversion of control vs Dependency Injection or ( DI vs IoC )

In Spring Dependency Injection and Inversion of control go hand in hand. DI is technique of suppling objects to the dependent objects and this process of suppling objects and by using IoC we are passing control of suppling objects to the container. We have defined DI and IoC in more details design pattern section.

Types of Dependency Injection

In Spring, DI can be achieved through various methods which are given below.

  • Constructor Injection:
  • Setter Injection
  • Autowiring

1. Spring Constructor Injection:

In this type of injection, we provide dependencies through constructor of the class. It is considered one of the best practices because it ensures that the required dependencies are provided at the time of object creation.

Example

public class OrderService {
    private final PaymentGateway paymentGateway;

    public OrderService(PaymentGateway paymentGateway) {
        this.paymentGateway = paymentGateway;
    }

    // ...
}

2. Spring Setter Injection:

Dependencies are injected through setter methods. This allows for more flexibility because you can change dependencies after the object has been created.

Example

public class OrderService {
    private PaymentGateway paymentGateway;

    public void setPaymentGateway(PaymentGateway paymentGateway) {
        this.paymentGateway = paymentGateway;
    }

    // ...
}

2. Spring Autowiring

Autowiring is a feature in Spring that allows the framework to automatically inject dependencies based on certain rules.

Example

@Component
public class ProductService {
    private ProductRepository productRepository;

    @Autowired
    public ProductService(ProductRepository productRepository) {
        this.productRepository = productRepository;
    }
    // ...
}

Benefits of Dependency Injection:

  • Loose Coupling Dependency Injection promotes loose coupling between classes, making it easier to change or replace dependencies without affecting the dependent class.
  • Testability It facilitates unit testing, as you can easily substitute real dependencies with mock objects during testing.
  • Reusability It encourages the reuse of components across different parts of your application.
  • Flexibility You can easily configure and manage dependencies through configuration files, allowing for configuration changes without modifying code.
  • Maintainability It improves code maintainability by clearly defining and managing dependencies.

Dependency Injection is a core concept in Spring that helps in building modular and maintainable applications. By choosing the appropriate injection method (constructor, setter, or autowiring) and configuring dependencies, you can achieve flexibility and ease of maintenance in your Spring-based projects.