Skip to lesson

Inversion of control in plain words

A ShopLite order needs a repository, a GST calculator and a notifier. Someone has to create these objects and connect them in the right order, and the bigger the app, the busier that someone gets.

Who creates the objects: the class or someone outside

Inversion of control (IoC) means a class no longer controls the creation of the objects it works with; something outside creates them and hands them in.

Example 1 builds the same service twice: once where the class makes its own notifier, once where main creates it and hands it in. Compare where EmailNotifier created appears.

Tight: OrderService creates its own EmailNotifier with new inside a method. Injected: main creates the EmailNotifier first, then creates OrderService and hands the notifier in through the constructor, so the code outside chooses. That move of the choice is inversion of control.

Example 1 · The same service, created two ways

WhoCreatesDemo.javaJava
interface Notifier {    void send(String to, String message);}
class EmailNotifier implements Notifier {    EmailNotifier() {        System.out.println("  EmailNotifier created");    }
    public void send(String to, String message) {        System.out.println("  EMAIL to " + to + ": " + message);    }}
// Version A: the class is in control of creating its helperclass SelfMadeOrderService {    private final Notifier notifier;
    SelfMadeOrderService() {        System.out.println("  SelfMadeOrderService creates its own notifier...");        this.notifier = new EmailNotifier();    }
    void placeOrder(int id, String email) {        notifier.send(email, "Order " + id + " confirmed");    }}
// Version B: control is inverted, the helper is handed inclass OrderService {    private final Notifier notifier;
    OrderService(Notifier notifier) {        System.out.println("  OrderService received: " + notifier.getClass().getSimpleName());        this.notifier = notifier;    }
    void placeOrder(int id, String email) {        notifier.send(email, "Order " + id + " confirmed");    }}
public class WhoCreatesDemo {    public static void main(String[] args) {        System.out.println("A: the class creates its helper");        new SelfMadeOrderService().placeOrder(1, "asha@example.com");
        System.out.println("B: main creates the helper and hands it in");        Notifier notifier = new EmailNotifier();        new OrderService(notifier).placeOrder(2, "asha@example.com");    }}
Output
A: the class creates its helper
  SelfMadeOrderService creates its own notifier...
  EmailNotifier created
  EMAIL to asha@example.com: Order 1 confirmed
B: main creates the helper and hands it in
  EmailNotifier created
  OrderService received: EmailNotifier
  EMAIL to asha@example.com: Order 2 confirmed

What this code does

  • In A, the EmailNotifier created line appears inside the service's constructor: the class controls creation.
  • In B, main creates the notifier first and the service only receives it. Control over creation has moved out: that is the inversion.

In normal beginner code each class creates what it needs, so the class is in control of its helpers. With constructor injection that control moves out: OrderService only receives a Notifier, and code outside decides which one to create. The direction of control is turned around, hence the name.

The benefit is the one from the last lesson: any notifier works, and a test can hand in a fake. The cost is that someone outside must now do the creating.

Wiring the whole app by hand in main

The composition root is the one place where an application's objects are created and connected; in a plain Java program it is the start of main.

Example 2 wires a small ShopLite app. The first lines of main create every object, and everything after them only uses those objects.

Example 2 · A small ShopLite app wired in main

ShopLiteHandWired.javaJava
import java.math.BigDecimal;import java.math.RoundingMode;import java.util.HashMap;import java.util.Map;
record Product(String sku, String name, BigDecimal price) {}
interface ProductRepository {    Product findBySku(String sku);}
class InMemoryProductRepository implements ProductRepository {    private final Map<String, Product> products = new HashMap<>();
    InMemoryProductRepository() {        products.put("MOB-RN13", new Product("MOB-RN13", "Redmi Note 13 5G", new BigDecimal("17999.00")));        products.put("ACC-AD141", new Product("ACC-AD141", "boAt Airdopes 141", new BigDecimal("1299.00")));    }
    public Product findBySku(String sku) {        return products.get(sku);    }}
class GstCalculator {    private final BigDecimal rate;
    GstCalculator(BigDecimal rate) {        this.rate = rate;    }
    BigDecimal withGst(BigDecimal amount) {        return amount.add(amount.multiply(rate)).setScale(2, RoundingMode.HALF_UP);    }}
interface Notifier {    void send(String to, String message);}
class EmailNotifier implements Notifier {    public void send(String to, String message) {        System.out.println("EMAIL to " + to + ": " + message);    }}
class OrderService {    private final ProductRepository products;    private final GstCalculator gst;    private final Notifier notifier;
    OrderService(ProductRepository products, GstCalculator gst, Notifier notifier) {        this.products = products;        this.gst = gst;        this.notifier = notifier;    }
    void placeOrder(String email, String sku, int quantity) {        Product p = products.findBySku(sku);        BigDecimal total = gst.withGst(p.price().multiply(BigDecimal.valueOf(quantity)));        notifier.send(email, quantity + " x " + p.name() + ", total Rs " + total + " with GST");    }}
public class ShopLiteHandWired {    public static void main(String[] args) {        // The composition root: every object is created and connected here, and only here        ProductRepository products = new InMemoryProductRepository();        GstCalculator gst = new GstCalculator(new BigDecimal("0.18"));        Notifier notifier = new EmailNotifier();        OrderService orders = new OrderService(products, gst, notifier);
        // From here on, the app just uses the objects        orders.placeOrder("asha@example.com", "ACC-AD141", 2);        orders.placeOrder("ravi@example.com", "MOB-RN13", 1);    }}
Output
EMAIL to asha@example.com: 2 x boAt Airdopes 141, total Rs 3065.64 with GST
EMAIL to ravi@example.com: 1 x Redmi Note 13 5G, total Rs 21238.82 with GST

What this code does

  • The first four lines of main are the composition root: repository, GST calculator, notifier, then the service that needs all three.
  • OrderService has no new for any collaborator. Its three dependencies all arrive through the constructor.
  • The demo applies a flat 18% GST: 2 × 1299.00 = 2598.00, plus 18% gives 3065.64. setScale(2, RoundingMode.HALF_UP) keeps two decimal places for rupees and paise.

To wire an app means to create its objects and connect each one to the objects it needs. The rule is simple: create everything at the top of main, from the classes that need nothing up to the classes that need the others. After that, the program only uses objects; it never creates collaborators.

Wiring in main is already proper dependency injection, with no framework at all. Many small Java tools are written exactly like this.

Trace the code

Wire two objects in main

class Repo {
String find() { return "Mouse"; }
}
class Service {
private final Repo repo;
Service(Repo repo) { this.repo = repo; }
void show() { System.out.println("Found " + repo.find()); }
}
public class WireDemo {
public static void main(String[] args) {
Repo repo = new Repo();
Service service = new Service(repo);
service.show();
}
}

Variables

repo
Repo object

Output

(nothing printed yet)

Line 15main creates the Repo first, because it needs nothing else.

Step 1 of 5
Read the composition root from top to bottom and you see the shape of the whole app: which classes exist and who talks to whom.

Why hand wiring gets painful as the app grows

Example 3 gives two classes a repository each by mistake. Watch what the report says after the order is placed.

Example 3 · Hand-wiring bug: two repositories instead of one

TwoRepositoriesBug.javaJava
import java.util.HashMap;import java.util.Map;
class StockRepository {    private final Map<String, Integer> stock = new HashMap<>();
    StockRepository() {        stock.put("HP Victus 15 Gaming", 5);    }
    int stockOf(String product) {        return stock.get(product);    }
    void reduce(String product, int quantity) {        stock.put(product, stock.get(product) - quantity);    }}
class OrderService {    private final StockRepository stock;
    OrderService(StockRepository stock) {        this.stock = stock;    }
    void placeOrder(String product, int quantity) {        stock.reduce(product, quantity);        System.out.println("Ordered " + quantity + " x " + product);    }}
class StockReport {    private final StockRepository stock;
    StockReport(StockRepository stock) {        this.stock = stock;    }
    void print(String product) {        System.out.println("Report: " + product + " stock = " + stock.stockOf(product));    }}
public class TwoRepositoriesBug {    public static void main(String[] args) {        System.out.println("Wrong wiring: each class gets its own repository");        OrderService orders = new OrderService(new StockRepository());        StockReport report = new StockReport(new StockRepository());        orders.placeOrder("HP Victus 15 Gaming", 2);        report.print("HP Victus 15 Gaming");
        System.out.println("Right wiring: one repository, shared");        StockRepository shared = new StockRepository();        OrderService orders2 = new OrderService(shared);        StockReport report2 = new StockReport(shared);        orders2.placeOrder("HP Victus 15 Gaming", 2);        report2.print("HP Victus 15 Gaming");    }}
Output
Wrong wiring: each class gets its own repository
Ordered 2 x HP Victus 15 Gaming
Report: HP Victus 15 Gaming stock = 5
Right wiring: one repository, shared
Ordered 2 x HP Victus 15 Gaming
Report: HP Victus 15 Gaming stock = 3

What this code does

  • In the wrong wiring, OrderService and StockReport each got their own new StockRepository(). The order reduced one copy; the report read the other, untouched copy, so it still says 5.
  • Nothing failed: no exception, no compiler error. Sharing one repository fixes it, and remembering to share is exactly the job a container takes over.

Hand wiring is fine for five classes. The ShopLite API by the end of this section has controllers, services and repositories for products, categories, customers and orders, plus a database pool and configuration: dozens of objects. Then three problems appear:

  • Order: you must create every object after the objects it needs, and keep that order right by hand.
  • Ripple: when one constructor gets a new parameter, main must change too.
  • Sharing: some objects, such as the repository that holds stock, must be one shared object. A second one compiles fine and gives wrong results.

Sharing is the worst, because nothing fails. The program runs and quietly reports the wrong stock.

Predict the output

One stock or two?

Read each program and pick what it prints.

Round 1 of 2

Orders and Report share one Stock.

class Stock { int units = 5; }
class Orders {
private final Stock stock;
Orders(Stock stock) { this.stock = stock; }
void sell() { stock.units--; }
}
class Report {
private final Stock stock;
Report(Stock stock) { this.stock = stock; }
int left() { return stock.units; }
}
public class SharedStock {
public static void main(String[] args) {
Stock shared = new Stock();
Orders orders = new Orders(shared);
Report report = new Report(shared);
orders.sell();
System.out.println(report.left());
}
}

A container that creates and connects objects for you

A container is an object that creates your application's objects, connects them, and keeps them so they can be shared.

Example 4 is a MiniContainer with one recipe per type. Asking it for OrderService makes it create what that service needs first.

Example 4 · MiniContainer: recipes in, wired objects out

MiniContainerDemo.javaJava
import java.util.HashMap;import java.util.Map;import java.util.function.Function;
// A tiny container: it keeps a recipe for each type and at most one object per typeclass MiniContainer {    private final Map<Class<?>, Function<MiniContainer, ?>> recipes = new HashMap<>();    private final Map<Class<?>, Object> objects = new HashMap<>();
    <T> void register(Class<T> type, Function<MiniContainer, T> recipe) {        recipes.put(type, recipe);    }
    <T> T get(Class<T> type) {        Object existing = objects.get(type);        if (existing != null) {            return type.cast(existing);              // already made: share the same object        }        Function<MiniContainer, ?> recipe = recipes.get(type);        if (recipe == null) {            throw new IllegalStateException("No recipe for " + type.getSimpleName());        }        T created = type.cast(recipe.apply(this));   // the recipe may ask for other types        System.out.println("  container created " + type.getSimpleName());        objects.put(type, created);        return created;    }}
interface Notifier {    void send(String to, String message);}
class EmailNotifier implements Notifier {    public void send(String to, String message) {        System.out.println("EMAIL to " + to + ": " + message);    }}
class StockRepository {    private int laptops = 5;
    void reduce(int quantity) {        laptops -= quantity;    }
    int laptops() {        return laptops;    }}
class OrderService {    private final StockRepository stock;    private final Notifier notifier;
    OrderService(StockRepository stock, Notifier notifier) {        this.stock = stock;        this.notifier = notifier;    }
    void placeOrder(String email, int quantity) {        stock.reduce(quantity);        notifier.send(email, quantity + " x HP Victus 15 Gaming confirmed");    }}
class StockReport {    private final StockRepository stock;
    StockReport(StockRepository stock) {        this.stock = stock;    }
    void print() {        System.out.println("Report: HP Victus 15 Gaming stock = " + stock.laptops());    }}
public class MiniContainerDemo {    public static void main(String[] args) {        MiniContainer container = new MiniContainer();
        container.register(OrderService.class,                c -> new OrderService(c.get(StockRepository.class), c.get(Notifier.class)));        container.register(StockReport.class, c -> new StockReport(c.get(StockRepository.class)));        container.register(StockRepository.class, c -> new StockRepository());        container.register(Notifier.class, c -> new EmailNotifier());
        System.out.println("Asking for OrderService:");        OrderService orders = container.get(OrderService.class);        System.out.println("Asking for StockReport:");        StockReport report = container.get(StockReport.class);
        orders.placeOrder("asha@example.com", 2);        report.print();        System.out.println("Same OrderService both times? "                + (orders == container.get(OrderService.class)));    }}
Output
Asking for OrderService:
  container created StockRepository
  container created Notifier
  container created OrderService
Asking for StockReport:
  container created StockReport
EMAIL to asha@example.com: 2 x HP Victus 15 Gaming confirmed
Report: HP Victus 15 Gaming stock = 3
Same OrderService both times? true

What this code does

  • The recipes are registered in a random order. When asked for OrderService, the container first creates the StockRepository and Notifier that its recipe asks for.
  • StockReport gets the same StockRepository that OrderService got, so the report shows 3. The two-repository bug of Example 3 cannot happen.
  • Asking again returns the stored object (true). Spring's default is the same: one shared object per type.

You tell the container how to make each type; it decides when and in what order, and makes sure each type exists only once. Ask for StockReport later, and it gets the same StockRepository as the service.

The Spring container is the same idea grown up. It reads your classes' constructors to find what each one needs, so you usually write no recipes at all, and it adds features such as configuration and clean shutdown. The next module shows it in action.

MiniContainer is a teaching model, not how to build real apps. Never write your own container for a project; use Spring's.

IoC (the idea) vs dependency injection (the technique)

Dependency injection (DI) is one technique of inversion of control: objects receive their dependencies from outside, usually through the constructor.

Example 5 shows inversion of control without any injection: your handler is registered with an HttpServer, and the server calls it.

Example 5 · IoC without DI: the server calls your handler

ServerCallsYouDemo.javaJava
import com.sun.net.httpserver.HttpExchange;import com.sun.net.httpserver.HttpHandler;import com.sun.net.httpserver.HttpServer;
import java.io.IOException;import java.io.OutputStream;import java.net.InetSocketAddress;import java.net.URI;import java.net.http.HttpClient;import java.net.http.HttpRequest;import java.net.http.HttpResponse;import java.nio.charset.StandardCharsets;
// Your code: it only says what to do when a request arrivesclass HelloHandler implements HttpHandler {    @Override    public void handle(HttpExchange exchange) throws IOException {        System.out.println("  handle() called by the server for " + exchange.getRequestURI());        byte[] body = "Hello from ShopLite".getBytes(StandardCharsets.UTF_8);        exchange.sendResponseHeaders(200, body.length);        try (OutputStream out = exchange.getResponseBody()) {            out.write(body);        }    }}
public class ServerCallsYouDemo {    public static void main(String[] args) throws Exception {        HttpServer server = HttpServer.create(new InetSocketAddress("localhost", 0), 0);        server.createContext("/hello", new HelloHandler());   // register, do not call        server.start();        System.out.println("Server started. main never calls handle() itself.");
        int port = server.getAddress().getPort();        HttpClient client = HttpClient.newHttpClient();        HttpRequest request = HttpRequest.newBuilder(URI.create("http://localhost:" + port + "/hello")).build();        HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());        System.out.println("Client got " + response.statusCode() + ": " + response.body());
        server.stop(0);    }}
Output
Server started. main never calls handle() itself.
  handle() called by the server for /hello
Client got 200: Hello from ShopLite

What this code does

  • main registers HelloHandler and starts the server, but never calls handle. When the request arrives, the server calls it: control over the flow is inverted.
  • Port 0 asks the operating system for any free port, so the demo never clashes with another program. The server is stopped at the end.

IoC is the general idea: your code does not drive everything itself; something outside calls into it or supplies it. DI is the form of IoC for creating objects. In Section 14 you wrote an HttpHandler that the HttpServer called when a request arrived; this is the Hollywood principle, "Don't call us, we'll call you". Spring does both: its container injects dependencies into your classes, and its web layer calls your controller methods when HTTP requests arrive.

Other examples of IoC, besides DI:

  • a server calling your handler
  • a button calling your click listener
  • JUnit calling your test methods

Next step

Check your understanding

12 quick questions