TExcelTAD
Home › Spring Boot › Dependency Injection & IoC

Dependency Injection & IoC

Dependency injection (DI) means an object receives the things it needs — its dependencies — from outside, instead of creating them itself. The Spring container (the ApplicationContext) creates your objects, figures out what each one needs, and passes the dependencies in. Because control over object creation moves from your code to the container, this is called inversion of control (IoC).

Without and with DI

Without DI, a class hard-wires its collaborators:

java
public class OrderService {
    private final PaymentGateway gateway = new StripeGateway("sk_live_123"); // fixed forever
}

You cannot swap the gateway for a fake in tests, you cannot choose another implementation per environment, and the API key is baked into the class. With DI the class only declares what it needs:

java
@Service
public class OrderService {
    private final PaymentGateway gateway;

    public OrderService(PaymentGateway gateway) {   // Spring passes a PaymentGateway bean
        this.gateway = gateway;
    }

    public String checkout(long cents) {
        return gateway.charge(cents);
    }
}

@Component
class FakeGateway implements PaymentGateway {
    public String charge(long cents) { return "charged " + cents + " cents"; }
}

Spring sees that OrderService has one constructor needing a PaymentGateway, finds the single bean implementing that interface (FakeGateway) and injects it. No @Autowired is needed when a class has exactly one constructor.

How a container resolves dependencies

The container's job is: to build X, first build everything X's constructor needs. This plain-Java container does that recursively, creating each object only once (a singleton) and detecting cycles:

java · try it yourself
import java.util.*;
import java.util.function.Function;

class Context {
    private final Map<String, Function<Context, Object>> definitions = new LinkedHashMap<>();
    private final Map<String, Object> singletons = new HashMap<>();
    private final Deque<String> creating = new ArrayDeque<>();

    void define(String name, Function<Context, Object> factory) { definitions.put(name, factory); }

    <T> T getBean(String name, Class<T> type) {
        Object existing = singletons.get(name);
        if (existing != null) return type.cast(existing);
        if (creating.contains(name)) throw new IllegalStateException("Circular reference: " + creating + " -> " + name);
        creating.push(name);
        System.out.println("creating " + name);
        Object bean = definitions.get(name).apply(this);
        creating.pop();
        singletons.put(name, bean);
        return type.cast(bean);
    }
}

interface PaymentGateway { String charge(long cents); }

class FakeGateway implements PaymentGateway {
    public String charge(long cents) { return "charged " + cents + " cents"; }
}

class OrderService {
    private final PaymentGateway gateway;
    OrderService(PaymentGateway gateway) { this.gateway = gateway; }
    String checkout(long cents) { return gateway.charge(cents); }
}

class Main {
    public static void main(String[] args) {
        Context ctx = new Context();
        ctx.define("orderService", c -> new OrderService(c.getBean("paymentGateway", PaymentGateway.class)));
        ctx.define("paymentGateway", c -> new FakeGateway());

        OrderService service = ctx.getBean("orderService", OrderService.class);
        System.out.println(service.checkout(1999));
        System.out.println(ctx.getBean("orderService", OrderService.class) == service);
    }
}
creating orderService
creating paymentGateway
charged 1999 cents
true

Notice the order: asking for orderService triggers creation of paymentGateway first, and the second getBean returns the cached instance.

Three ways to inject

Style Example Use it?
Constructor OrderService(PaymentGateway g) Yes — fields can be final, easy to test, dependencies are obvious
Setter @Autowired void setGateway(PaymentGateway g) only for truly optional dependencies
Field @Autowired private PaymentGateway gateway; avoid — hides dependencies, needs reflection to test

Tip: With constructor injection, a unit test needs no Spring at all: new OrderService(new FakeGateway()). That is one of the biggest practical benefits of DI.

When there is more than one candidate

If two beans implement PaymentGateway, Spring cannot decide and fails at startup:

bash · try it yourself
./mvnw spring-boot:run
***************************
APPLICATION FAILED TO START
***************************

Description:

Parameter 0 of constructor in com.example.shop.OrderService required a single bean, but 2 were found:
	- fakeGateway: defined in file [/home/me/shop/target/classes/com/example/shop/FakeGateway.class]
	- stripeGateway: defined in file [/home/me/shop/target/classes/com/example/shop/StripeGateway.class]

Action:

Consider marking one of the beans as @Primary, updating the consumer to accept multiple beans, or using @Qualifier to identify the bean that should be consumed

The fixes the message suggests:

java
@Component
@Primary                                 // the default choice
class StripeGateway implements PaymentGateway { ... }

@Service
class OrderService {
    OrderService(@Qualifier("fakeGateway") PaymentGateway gateway) { ... }  // explicit choice
}

@Service
class PaymentRouter {
    PaymentRouter(List<PaymentGateway> all) { ... }  // inject every implementation
}

Circular dependencies

If A needs B and B needs A through their constructors, neither can be created first, so startup fails. (Since Spring Boot 2.6, cycles through field or setter injection are rejected by default as well.) Our mini container detects it the same way:

java · try it yourself
import java.util.*;
import java.util.function.Function;

class Context {
    private final Map<String, Function<Context, Object>> defs = new HashMap<>();
    private final Deque<String> creating = new ArrayDeque<>();
    void define(String name, Function<Context, Object> f) { defs.put(name, f); }
    Object getBean(String name) {
        if (creating.contains(name)) {
            List<String> chain = new ArrayList<>(creating);
            Collections.reverse(chain);
            throw new IllegalStateException("cycle: " + String.join(" -> ", chain) + " -> " + name);
        }
        creating.push(name);
        try { return defs.get(name).apply(this); } finally { creating.pop(); }
    }
}

record A(Object b) {}
record B(Object a) {}

class Main {
    public static void main(String[] args) {
        Context ctx = new Context();
        ctx.define("a", c -> new A(c.getBean("b")));
        ctx.define("b", c -> new B(c.getBean("a")));
        try {
            ctx.getBean("a");
        } catch (IllegalStateException e) {
            System.out.println(e.getMessage());
        }
    }
}
cycle: a -> b -> a

A cycle usually means two classes have too many responsibilities; extract the shared logic into a third bean instead of fighting the container.

Test yourself

Which injection style does the Spring team recommend for required dependencies?

  1. Field injection
  2. Setter injection
  3. Constructor injection
  4. Static injection

Two beans implement the same interface and a constructor asks for one. What happens without extra hints?

  1. Spring picks one at random
  2. Spring injects the first alphabetically
  3. Startup fails: a single bean was required but 2 were found
  4. Both are injected as a list

Is @Autowired required on a class's only constructor?

  1. Yes, always
  2. No, a single constructor is used automatically
  3. Only for records
  4. Only in tests