Repaso
Español

Explain Inversion of Control and Dependency Injection, and why Spring uses them.

Answer

  • Inversion of Control: your code no longer controls the creation and lifecycle of its collaborators; a container does.
  • Dependency Injection is the way IoC is applied: a class declares dependencies (constructor parameters) and the container supplies them.
  • Spring scans for beans (@Component, @Service...), builds the object graph at startup and injects dependencies.
  • Benefits: loose coupling (depend on interfaces), easy testing with mocks, central configuration, lifecycle management.
  • Example: OrderService(PaymentGateway g); in production Spring gives a Stripe gateway, in tests you pass a mock.

Key terms

Practice this question in Repaso