How do I inject dependencies using constructor injection?

Use constructor injection by declaring your dependency as a private final field and accepting it as a constructor parameter. Spring will create the dependency bean and pass it into the constructor automatically.

Example:

import org.springframework.stereotype.Component;

@Component
public class MyDependency {

    public void doSomething() {
        System.out.println("Dependency logic executed.");
    }
}
import org.springframework.stereotype.Service;

@Service
public class MyService {

    private final MyDependency myDependency;

    public MyService(MyDependency myDependency) {
        this.myDependency = myDependency;
    }

    public void doWork() {
        myDependency.doSomething();
    }
}

Spring can inject MyDependency because:

  1. MyDependency is a Spring bean, for example annotated with @Component.
  2. MyService is also a Spring bean, for example annotated with @Service.
  3. MyService has a constructor that requires MyDependency.

In modern Spring, if the class has only one constructor, you usually do not need @Autowired:

@Service
public class MyService {

    private final MyDependency myDependency;

    public MyService(MyDependency myDependency) {
        this.myDependency = myDependency;
    }
}

If you use Lombok, you can make it shorter:

import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

@Service
@RequiredArgsConstructor
public class MyService {

    private final MyDependency myDependency;

    public void doWork() {
        myDependency.doSomething();
    }
}

Constructor injection is recommended because it makes dependencies explicit, allows fields to be final, improves testability, and prevents partially initialized objects.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.