Spring dependency injection tutorial

Dependency injection spring example. Spring dependency injection example in java.


Injection is a process of passing the dependency to a dependent object.

Dependency Injection (DI):

Dependency Injection (DI) is a design pattern that implements inversion of control principle for resolving dependencies. It allows a programmer to remove hard coded dependencies so that the application becomes loosely coupled and extendable.

Let us discuss object dependency with below example:

public class Student {
private Address address;
public Student() {
address = new Address();
In above example Student class requires an Address object and it is responsible for initializing and using the Address object. If Address class is changed in future then we have to make changes in Student class also. This approach makes tight coupling between Student and Address objects. We can resolve this problem using dependency injection design pattern. i.e. Address object will be implemented independently and will be provided to Student when Student is instantiated by using constructor-based or setter-based dependency injection.

Types of dependency Injection:

1. Constructor-based Dependency Injection.
2. Setter-based Dependency Injection.

No comments: