What is Dependency Injection in Spring?

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).