What is Dependency Injection in Spring?

Why Interviewers Ask This

This is a classic screening question for Spring Boot roles. Hiring managers ask it early in interviews to gauge your baseline understanding and determine if you can communicate technical concepts clearly.

Answer

Dependency Injection (DI) is a core Spring Framework pattern where objects don't create their dependencies themselves — they declare them and Spring's IoC (Inversion of Control) container provides them. Types of DI in Spring: (1) Constructor Injection (recommended): @Service public class OrderService { private final PaymentService paymentService; private final EmailService emailService; @Autowired // optional with single constructor in Spring 4.3+ public OrderService(PaymentService paymentService, EmailService emailService) { this.paymentService = paymentService; this.emailService = emailService; } }. Benefits: dependencies are final (immutable), easier testing (pass mocks via constructor), clearly visible dependencies; (2) Setter Injection: @Autowired public void setPaymentService(PaymentService ps) { this.paymentService = ps; }. Use for optional dependencies; (3) Field Injection (avoid): @Autowired private PaymentService paymentService;. Cannot make final, harder to test, hides dependencies — avoid in production code. @Autowired: Spring automatically wires the bean of the matching type. @Qualifier: when multiple beans of the same type exist: @Autowired @Qualifier("primaryPaymentService"). @Primary: mark a bean as the default when multiple exist. IoC Container: Spring's ApplicationContext manages bean creation, lifecycle, and injection. Beans are singletons by default (one instance per application context).

Pro Tip

Before answering, structure your response: one-line definition → real-world analogy → concrete example from a project. This makes even complex Spring Boot answers easy to follow.