Medium15 minSpring Boot Fundamentals
UpdatedAug 5, 2026
Edit

Spring Boot Dependency Injection

Question Variations

  • "Why is constructor injection preferred over field injection?"
  • "How do you inject one of several implementations?"
  • "When should a bean be request-scoped?"

Why This Is Asked

Dependency injection is central to Spring design. This question evaluates constructor injection, bean ownership, and how to resolve multiple implementations safely.

Key Concepts

  • Constructor injection makes required dependencies explicit and testable.
  • Components and @Bean methods define container-managed objects.
  • @Primary and @Qualifier disambiguate multiple candidates.
  • Bean scope should match lifecycle and concurrency needs.

Question Variations

  • “Why is constructor injection preferred over field injection?”
  • “How do you inject one of several implementations?”
  • “When should a bean be request-scoped?”

Answers by Technology

+ Add Variant
Spring BootImprove this answer ✏️

Expected Answer (Spring Boot 4.1.0 / Java 17+)

Prefer constructor injection for required dependencies. It makes the object valid after construction, supports immutable fields, and permits a plain unit test to provide fakes without Spring. Spring discovers stereotype components or invokes @Bean methods to create managed instances. If several beans implement the same interface, use @Qualifier for an explicit choice or @Primary for a sensible default.

Why It Matters

Explicit dependencies make component lifecycles, tests, and wiring failures much easier to reason about.

Code Example

@Service
class InvoiceService {
  private final TaxCalculator taxes;
  InvoiceService(@Qualifier("standardTax") TaxCalculator taxes) { this.taxes = taxes; }
}

Common Mistakes

  • Using field injection: Dependencies are hidden and tests need reflection or a container.
  • Resolving ambiguity by injecting a random implementation: Behavior changes as more beans are added.

Follow-up Questions

  • When use @Primary? (Answer: When one implementation is the normal default.)
  • Why might request scope be needed? (Answer: For state that must exist once per HTTP request.)