Repaso
EspaƱol

What is Dependency Injection (DI)?

Options

  1. A class builds every object that it needs with new
  2. A class declares needs and a container provides them (Correct option)
  3. Copying a database table into a different schema
  4. A technique to inject JavaScript code into web pages

Answer

A class declares what it needs and an external container provides those objects, usually through the constructor

Why

Without DI, OrderService would write new PaymentGateway() inside itself, so it is tied to that exact class and hard to test.

With DI, OrderService receives a PaymentGateway (usually an interface) through its constructor. Spring decides which implementation to give.

Benefits: loose coupling, easy replacement, and in unit tests you can pass a fake or mock.

@Service
public class OrderService {
    private final PaymentGateway gateway;

    public OrderService(PaymentGateway gateway) {   // injected by Spring
        this.gateway = gateway;
    }
}

Remember

Don't create your dependencies; receive them.

Key terms

Practice this question in Repaso