Spring Framework FAQ: Top Questions
38. How does Spring manage dependency injection?
Spring performs Dependency Injection (DI) to decouple object creation and its dependencies. It supports constructor, setter, and field injection.
📘 Types of Injection:
- Constructor Injection: Dependencies provided at object creation.
- Setter Injection: Dependencies injected via setters.
- Field Injection: Using
@Autowired
directly on fields.
📥 Example:
@Component
public class OrderService {
private final PaymentService paymentService;
@Autowired
public OrderService(PaymentService paymentService) {
this.paymentService = paymentService;
}
}
🏆 Expected Output:
OrderService is created with a fully injected PaymentService bean.
🛠️ Use Cases:
- Cleaner code, easier testing and maintenance.
- Supports both optional and mandatory dependencies.