What is IOC and DI?

IoC (Inversion of Control) is a design principle in which the responsibility of creating and managing objects is transferred from the application code to a container or framework. DI (Dependency Injection) is the most common technique used to implement IoC by providing required dependencies from outside rather than creating them inside the class.

Key Points: • IoC shifts object creation and lifecycle management to the Spring container. • DI injects required dependencies into a class, reducing tight coupling between components. • DI improves code maintainability, reusability, and testability. • Spring supports Constructor Injection, Setter Injection, and Field Injection. • IoC and DI help build loosely coupled and scalable applications.

Example: Consider a UserService class that requires a UserRepository. Instead of creating the UserRepository object using the new keyword, Spring automatically injects it into UserService. This makes the code more flexible and easier to test.

Code Example:

@Service
public class UserService {

    private final UserRepository userRepository;

    public UserService(UserRepository userRepository) {
        this.userRepository = userRepository;
    }
}

Interview Tip: A concise interview answer is:

"IoC is a design principle where the Spring container manages object creation and lifecycle. DI is a technique used to achieve IoC by injecting required dependencies into a class instead of letting the class create them. This promotes loose coupling and improves maintainability."