Video in progress

Are the Dependency Inversion principle and Dependency Injection the same thing?

No. Dependency Inversion is a design principle: a high-level module should depend on an abstraction, not on a concrete low-level class. Dependency Injection is a technique for giving those dependencies to an object from outside (for example, through the constructor); it is one way to reach DIP.

📖 Answer

A DIP violation:

class OrderService {
    private final MySqlOrderDao dao = new MySqlOrderDao();   // a concrete class, created inside
}

OrderService can no longer live without MySQL, and testing it needs a real database.

A DIP-friendly version:

interface OrderRepository { void save(Order o); }

class OrderService {
    private final OrderRepository repo;
    OrderService(OrderRepository repo) { this.repo = repo; }   // DI through the constructor
}

Notice there are two things here:

  • inversion: OrderService now depends on an interface, and the interface "belongs" to the business layer;
  • injection: someone from outside supplies the concrete object: Spring, or in a test you yourself with new OrderService(new InMemoryOrderRepository()).

DIP is possible without DI (for example through a factory or ServiceLoader), and DI is possible without DIP (passing a concrete class into the constructor). But in practice the two go together.