Spring Framework FAQ: Top Questions
2. What is Dependency Injection in Spring?
Dependency Injection (DI) is a design pattern in which objects receive their dependencies from an external source rather than creating them internally. Spring implements DI to achieve loose coupling and greater testability.
📘 Types of Injection:
- Constructor Injection
- Setter Injection
- Field Injection (not recommended)
📥 Example:
public class Car {
private Engine engine;
@Autowired
public Car(Engine engine) {
this.engine = engine;
}
}
🏆 Expected Output:
Spring injects the Engine bean into Car via constructor.
🛠️ Use Cases:
- Promotes cleaner and more testable code.
- Allows decoupling of components.