Spring Boot Tutorial 0/110 lessons ~6 min read Lesson 8

    Dependency Injection

    Dependency Injection (DI) is Spring's superpower.

    Course progress0%
    Focus
    4 guided sections
    Practice signal
    Examples included
    Career prep
    Foundation builder

    Introduction

    Dependency Injection (DI) is Spring's superpower. Instead of new-ing collaborators inside your class, you declare them as constructor parameters and Spring wires them in. The result: testable, swappable, decoupled code.

    Understanding the topic

    Three flavours of injection — only one is correct in 2026:

    • Constructor injection — required, immutable, easy to test. Use this.
    • ⚠️ Setter injection — for optional deps only.
    • Field injection (@Autowired private Foo foo) — hides dependencies, breaks final, hostile to testing. Avoid.

    Informative example

    Constructor injection (no @Autowired needed since Spring 4.3):

    ts
    @Service
    public class OrderService {
    private final OrderRepository repo;
    private final PricingClient pricing;
    public OrderService(OrderRepository repo, PricingClient pricing) {
    this.repo = repo;
    this.pricing = pricing;
    }
    public Order place(NewOrder cmd) {
    int total = pricing.quote(cmd.items());
    return repo.save(new Order(cmd.userId(), total));
    }
    }

    Best practices

    • Always use constructor injection; mark fields final.
    • Prefer Lombok's @RequiredArgsConstructor to remove boilerplate.
    • If a class has 6+ dependencies, it's doing too much — split it.
    Ready to mark this lesson complete?Track your journey across the entire course.