Spring Boot & Microservices (50 Qs)•Part 1: Spring Core, Auto-Configuration & Architecture (1 - 10)
What is Inversion of Control (IoC) and Dependency Injection (DI) in Spring?
senior LevelMost AskedCode ExampleDependency InjectionSystem Design
In Simple Words:
- Inversion of Control (IoC): Instead of a class instantiating its dependencies with
new OrderRepository(), control of object lifecycle and creation is inverted and delegated to the Spring IoC Container (ApplicationContext). - Dependency Injection (DI): The mechanism where the IoC container injects dependent objects into a bean at runtime.
- Best Practice: Constructor injection with
finalfields because it guarantees immutability, facilitates unit testing without mocking Spring, and preventsNullPointerException.
java
@Service
public class OrderService {
private final OrderRepository orderRepository;
private final NotificationService notificationService;
// Constructor Injection (Preferred over field injection @Autowired)
public OrderService(OrderRepository orderRepository, NotificationService notificationService) {
this.orderRepository = orderRepository;
this.notificationService = notificationService;
}
}