Dependency injection is the design pattern where an object's dependencies are provided to it by an external container rather than the object creating them itself. In Spring MVC, this means controllers declare what services or repositories they need, and the Spring IoC container supplies those instances automatically.
Key Points: • Instead of using new to create a service, a controller declares a dependency (often as a constructor parameter) and lets Spring supply it. • The Spring container reads component definitions from stereotype annotations (@Component, @Service, @Repository, @Controller) or explicit @Bean methods and wires them together at startup. • Constructor injection is preferred because it makes required dependencies explicit and supports immutable, final fields. • Loose coupling from DI makes classes easier to test, since real dependencies can be swapped for mocks without changing the class itself. • DI also enables Spring to manage the lifecycle and scope of beans centrally, rather than every class managing its own dependencies.
Example: A controller that needs to send emails declares a final EmailService field set through its constructor; Spring provides the real EmailService bean in production, while a test can pass in a mock EmailService instead.
Interview Tip: A concise interview answer is:
"Dependency injection means Spring's IoC container creates and wires up the objects a class needs instead of the class creating them itself. In practice, I declare dependencies as constructor parameters, and Spring resolves and injects the right beans automatically, which keeps the code loosely coupled and easy to test with mocks."