Skip to main content
InterviewHubPRO
Section Overview
Q1

Question 1 of 50

Part 1: Spring Core, Auto-Configuration & Architecture (1 - 10)

2%
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 final fields because it guarantees immutability, facilitates unit testing without mocking Spring, and prevents NullPointerException.
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;
    }
}