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

    Dependency Injection

    Dependency injection means OrderService names a PricingClient and the container passes the bean it already manages.

    Course progress0%
    Focus
    12 guided sections
    Practice signal
    Examples included
    Career prep
    Interview Q&A included

    Introduction

    Dependency injection means OrderService names a PricingClient and the container passes the bean it already manages. The service does not call new PricingClient(). That inversion is what makes checkout rules testable.

    On Spring Boot 3 / Java 21 the standard is constructor injection into final fields. One constructor is selected automatically — @Autowired has been optional since Spring Framework 4.3. A unit test passes fakes with new and never starts a context. Field injection hides the graph and cannot assign final. ObjectProvider<T> is the usual way to express an optional or lazy collaborator.

    Two beans of one type fail startup with NoUniqueBeanDefinitionException. @Qualifier("promo") on the parameter is an explicit choice; @Primary is only the fallback. List<PricingClient> injects every match, which is the right shape for a fan-out.

    Since Boot 2.6, circular constructors fail unless spring.main.allow-circular-references=true. Leave the flag off. Extract a third type, publish an event, or look the dependency up through ObjectProvider. A half-initialized payment bean is worse than a failed boot.

    Purpose of this lesson

    Wire Orders through constructors, disambiguate two pricing beans, and test place with new OrderService(fake) — reserve @SpringBootTest for HTTP and JPA.

    Understanding the topic

    Spring matches parameters by type, then by qualifier. Dependencies exist before your constructor runs.

    • Constructor: required collaborators, final fields, plain new in tests.
    • Several constructors: mark the one Boot should call with @Autowired.
    • Ambiguity: qualifier on the parameter, or a single @Primary as the boring default.
    • Cycles: constructor cycles fail fast. Field injection used to hide them behind an early reference.

    Step-by-step explanation

    1. Define PricingClient as a one-method interface at the service boundary.
    2. Assign private final fields from a single constructor. Skip @Autowired.
    3. Stereotype the implementation with @Service so component scan registers it.
    4. If startup reports a duplicate type, add @Qualifier and cover the choice with a unit test that does not boot Spring.

    Informative example

    Price, then place. The test implements the interface with a lambda.

    java
    public interface PricingClient {
    int quoteCents(String sku, int qty);
    }
    @Service
    public class OrderService {
    private final PricingClient pricing;
    public OrderService(PricingClient pricing) {
    this.pricing = pricing;
    }
    public PlacedOrder place(String sku, int qty) {
    return new PlacedOrder(sku, pricing.quoteCents(sku, qty));
    }
    }
    record PlacedOrder(String sku, int amountCents) {}

    Two beans need a qualifier at the injection point:

    java
    @Bean @Qualifier("promo")
    PricingClient promoPrice() { return (sku, qty) -> 3999; }
    @Service
    class PromoOrderService {
    private final PricingClient pricing;
    PromoOrderService(@Qualifier("promo") PricingClient pricing) {
    this.pricing = pricing;
    }
    }

    Real-world use

    In TechLearningPro Orders, place asks PricingClient for cents and an inventory port to reserve the SKU. Promo tests pass a lambda and never bind port 8080. The HTTP client behind the interface can change later. A constructor with six services means the class is also doing tax, fraud, mail, and audit — split it.

    Security implications

    The container wires whatever type matches. A sloppy default sends Orders to the wrong payment host.

    • Inject the pricing port into the service and the service into the controller. A controller holding a DataSource or an admin client will eventually expose it.
    • Do not store the current user or a bearer token on a singleton field. The next request shares that instance.
    • A lazy proxy that hides a cycle can run a security filter before its allow-list is set. Fail the boot.

    Best practices

    • One constructor and final fields. Depend on interfaces at service boundaries.
    • Put @Qualifier beside the business choice. Use @Primary only for the default.
    • Inject Clock rather than calling Instant.now(), so tests freeze time.
    • Treat more than about four collaborators as a reason to split the type.

    Common mistakes

    • new CatalogPricingClient() inside the service skips the container, so transactions and test fakes never apply.
    • Field @Autowired, or mixing @RequiredArgsConstructor with a second handwritten constructor so Spring picks the empty one.
    • @Primary left on a sandbox payment client. Unqualified injection points follow it.
    • allow-circular-references turned on to green the boot. One bean then sees the other mid-initialization.

    Advanced interview questions

    Interview Prep

    Practice concise answers, then expand each card for the explanation.

    3 questions
    1BeginnerQuestionWhy prefer constructor injection on Boot 3?+

    Answer

    The signature lists the dependencies, fields stay final, and tests call new. A single constructor needs no @Autowired. Field injection hides the graph and needs reflection.
    2IntermediateQuestionWhat happens when two beans implement PricingClient?+

    Answer

    NoUniqueBeanDefinitionException at startup, unless the parameter has @Qualifier, one bean is @Primary, or you inject List<PricingClient>. The qualifier wins when both are present.
    3AdvancedQuestionBoot reports a dependency cycle. What do you change?+

    Answer

    Redraw the graph: extract a type, emit an event, or use ObjectProvider. spring.main.allow-circular-references=true is a migration switch, not the design of a new Orders service.

    Hands-on exercise

    Lab. Constructor-inject PricingClient and assert place with (sku, qty) -> 4999. Add a second bean, read NoUniqueBeanDefinitionException, and fix it with @Qualifier("promo").

    Summary

    Orders injection is a constructor contract: PricingClient in, PlacedOrder out. Boot supplies the production client, tests supply a lambda, and a refused cycle protects you from a half-built bean.

    Ready to mark this lesson complete?Track your journey across the entire course.