Dependency Injection in Spring Example

In this tutorial you are going to learn what Dependency Injection in Spring is, how it works and how you can use it.

spring-featured-image

What is Dependency Injection?

Dependency Injection is one of the fundamentals of Spring which you must know.

When you create a complex application, chances are you are going to have different objects work together. Ideally, you would want these object to be independent of each other. This design principle is of Inversion of Control and it emphasizes that Java classes are kept independent of each other and then the ocntainer will free them from objection creation and maintenance. If you are not familiar with IoC, I strongly encourage you to read this article about the topic.




Think about how you would have to create an object dependency following the traditional approach. You would have to create an instance variable of the type of the object and then either have a constructor and a setter method or one (constructor/setter method). Something like this:

public class Employee{
	private Company company;
	
	public Employee() {
		company = new Company();
	}
}

When we use DI however, it will look like so:

public class Employee{
	private Company company;
	
	public Employee(Company company) {
		this.company= company;
	}
}

Can you see why the second example is better? Because now Employee does not need to worry about Company implementation, it will be implemented independently of Employee, and will be provided to the Employee via the constructor or in other words at the time of the initialization of the Employee. In other words, an employee won’t be able to exist without being a part of a company. Otherwise, he wouldn’t be an employee.

The dependency (the Company) is being injected into the Employee class via constructor.

There are 2 types of DI:

  1. Constructor injection
    1. when injected via class constructor
  2. Setter-based dependency injection
    1. when injected using a setter method

Let’s see how we can achieve DI using a setter method.

Setter-based Dependency Injection

When using a setter-based injection, the container will call setter methods of the class after having invoked a no-argument constructor or method to instantiate the bean. If you are unfamiliar with bean in Spring, you can read this article.

This is how setter-based DI is implemented:

@Bean
public void setCompany(Company company) {
   this.company = company;
}

As to which type to use, it is often recommended to use Constructor DI for mandatory dependencies and setters for optional dependencies.

Thanks to DI, now the Employee class does not need to look up Company and neither does it know the location nor the class of it.

0 0 votes
Article Rating
guest
0 Comments
Inline Feedbacks
View all comments