DEV Community

Cover image for Spring - Dependency Injection
Yiğit Erkal
Yiğit Erkal

Posted on • Updated on

Spring - Dependency Injection

Dependency Injection is the most important feature of Spring framework. It is a design pattern where the dependencies of a class are injected from outside. It ensures loose-coupling between classes.

In a Spring MVC application, the controller class has dependency of service layer classes and the service layer classes have dependencies of DAO layer classes. Suppose class A is dependent on class B.


In normal coding, you will create an object of class B using ‘new’ keyword and call the required method of class B. However, what if you can tell someone to pass the object of class B in class A? Dependency injection does this. You can tell Spring, that class A needs class B object and Spring will create the instance of class B and provide it in class A. In the above example, we can see that we are passing the control of objects to Spring framework, this is called Inversion of Control (IOC) and Dependency injection is one of the principles that enforce IOC.

class ClassA {
  ClassB classB = new ClassB();

  int doCalculation() {
    return classB.calculate();
Enter fullscreen mode Exit fullscreen mode

Here comes the @Autowired keyword

❗Before Spring 4.3, we had to add an @Autowired annotation to the constructor. With newer versions, this is optional if the class has only one constructor.

Thanks to the @Autowired annotation, we can inject the values ​​in a bean into another bean and use them while preserving their values in Spring. There are multiple ways inject but among "Property Based", "Setter Based" and "Constructor Based" we will use "Constructor Based" to benefit from Dependency Injection. You may google them for further details and the see the differences.

This is why we use constructor based injection "All required dependencies are available at initialization time"

Code please...

We'll see that an instance of MyBeanToInject is injected by Spring as an argument to the MyService constructor:

public class MyService {
    private MyBeanToInject myBeanToInject;
    public MyService(MyBeanToInject myBeanToInject) {
        this.myBeanToInject = myBeanToInject;
Enter fullscreen mode Exit fullscreen mode

To sum up 🏁


  • A basic benefit of dependency injection is decreased coupling between classes and their dependencies.
  • By removing a client's knowledge of how its dependencies are implemented, programs become more reusable, testable and maintainable.
  • Dependency injection reduces boilerplate code, since all dependency creation is handled by a singular component


  • Overuse can cause management problems and other problems.
  • Many compile time errors are passed to runtime

Discussion (0)