What Dependency Injection Really Is and Why Spring Uses It
Dependency injection means a class receives its collaborators instead of building them. See what that buys in tests and wiring, and what Spring adds.

Dependency injection sounds like framework magic, and it is the opposite. It is a plain idea that predates Spring by decades: a class should receive the things it needs instead of building them itself. Spring is a machine that automates the handing-over once you have a few hundred classes. Understanding the idea without the framework makes every Spring error message, from missing beans to circular dependencies, easier to read, because you can see what the container was trying to do on your behalf. This post builds the same small program three times: with hard-wired dependencies, with hand-written injection, and with Spring. Then it weighs the costs and says when you do not need a container at all. Examples use Java 25 and Spring Framework 7.
The class that builds its own parts
An order service needs to charge a payment and send a receipt. The first version creates its collaborators directly:
package dev.javahacks.di;
public class OrderService {
private final StripeGateway gateway = new StripeGateway("sk_live_example");
private final SmtpMailer mailer = new SmtpMailer("smtp.example.test", 587);
public String place(String customerEmail, long cents) {
String chargeId = gateway.charge(cents);
mailer.send(customerEmail, "Receipt for " + chargeId);
return chargeId;
}
}It compiles and runs, and three problems are already baked in. You cannot test place without calling the real payment gateway and the real mail server, because both are constructed inside. You cannot change the gateway without editing this class. And the credentials sit in source code, because the class that uses a gateway is also deciding how to configure one. The class has two jobs, doing its own work and building the world it works in, and the second job is the one that makes it rigid.
The same class, with the dependency handed in
Give the class the parts through its constructor, and describe each part by what it does:
package dev.javahacks.di;
public interface PaymentGateway {
String charge(long cents);
}package dev.javahacks.di;
public interface Mailer {
void send(String to, String body);
}package dev.javahacks.di;
public class OrderService {
private final PaymentGateway gateway;
private final Mailer mailer;
public OrderService(PaymentGateway gateway, Mailer mailer) {
this.gateway = gateway;
this.mailer = mailer;
}
public String place(String customerEmail, long cents) {
String chargeId = gateway.charge(cents);
mailer.send(customerEmail, "Receipt for " + chargeId);
return chargeId;
}
}That is dependency injection, entirely. The word "injection" overstates what happened: the class declares what it needs and someone else supplies it. The payoff is immediate in a test, with no framework and no mocks library:
package dev.javahacks.di;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.ArrayList;
import java.util.List;
import org.junit.jupiter.api.Test;
class OrderServiceTest {
@Test
void sendsAReceiptForTheCharge() {
List<String> sent = new ArrayList<>();
PaymentGateway fakeGateway = cents -> "ch_" + cents;
Mailer fakeMailer = (to, body) -> sent.add(to + ": " + body);
var service = new OrderService(fakeGateway, fakeMailer);
String id = service.place("[email protected]", 4999);
assertThat(id).isEqualTo("ch_4999");
assertThat(sent).containsExactly("[email protected]: Receipt for ch_4999");
}
}OrderServiceTest > sendsAReceiptForTheCharge() PASSEDThe test runs in milliseconds, touches no network and fails only if OrderService is wrong. The wiring has to live somewhere, and in a small program it lives in main:
public class Main {
public static void main(String[] args) {
var gateway = new StripeGateway(System.getenv("STRIPE_KEY"));
var mailer = new SmtpMailer("smtp.example.test", 587);
var service = new OrderService(gateway, mailer);
service.place("[email protected]", 4999);
}
}This is called "poor man's DI" and it is a perfectly good design. Every dependency is visible, the compiler checks it, and the only cost is that you write the new calls. The calls grow in number, and in order, as the program does: with forty classes, main is forty lines in the right sequence, and one class constructed in two places is a bug waiting to happen. That is the pain Spring removes.
What Spring adds
Spring is a registry of recipes plus an engine that follows them. You declare which classes are components, the container works out the construction order from the constructors' parameter types, builds each object once, and passes it to whoever asks.
@Component
class StripeGateway implements PaymentGateway {
private final String apiKey;
StripeGateway(@Value("${stripe.key}") String apiKey) {
this.apiKey = apiKey;
}
public String charge(long cents) {
return "ch_" + cents; // the real call to the provider goes here
}
}@Component
class SmtpMailer implements Mailer {
public void send(String to, String body) { /* send via SMTP */ }
}
@Service
public class OrderService {
private final PaymentGateway gateway;
private final Mailer mailer;
public OrderService(PaymentGateway gateway, Mailer mailer) { // no @Autowired needed
this.gateway = gateway;
this.mailer = mailer;
}
// place(...) is unchanged
}At startup the container scans for annotated classes, notes that OrderService needs a PaymentGateway and a Mailer, finds the one bean of each type, and calls the constructor. The class itself did not change at all between the hand-wired version and this one: the same constructor, the same fields, the same test. That is the point. Spring did not introduce the idea, it automated the main method. The machinery, including the order in which beans are made, is in how the Spring container really works.
When the container cannot satisfy a constructor, it tells you precisely what it was looking for. Two beans of the type Mailer and it cannot choose, which gives the message in NoUniqueBeanDefinitionException and qualifiers. Two beans that need each other cannot be built in any order, which is the subject of fixing circular dependencies.
Three ways to inject, and one to prefer
Spring accepts a dependency in three places.
// Constructor injection
@Service
class A {
private final Repo repo;
A(Repo repo) { this.repo = repo; }
}
// Setter injection
@Service
class B {
private Repo repo;
@Autowired void setRepo(Repo repo) { this.repo = repo; }
}
// Field injection
@Service
class C {
@Autowired private Repo repo;
}Prefer the constructor. The field can be final, so the object is complete once constructed and cannot change under you. It cannot be built half-wired: new A(null) is visible at the call site, and a missing dependency is a compile error in a test, not a NullPointerException at runtime. A class with six constructor parameters is telling you something about its design, which hidden field injection would never do. Field injection is the one that prevents the plain-Java test above, since a private @Autowired field cannot be set without reflection or a Spring test context. Setter injection suits a genuinely optional dependency. The official wording is in the constructor-based versus setter-based DI section of the reference.
What you pay
DI is not free, and the costs are worth naming.
Indirection. "Where does this get created?" has the answer "somewhere in a container", and your IDE needs Spring support to navigate it. A bug in wiring is found at startup, not at compile time.
Startup and reflection. The container scans classes, reads annotations and builds proxies. For a typical service that is a second or two; for a function that must start in milliseconds it matters, and it is the reason compile-time frameworks and native images exist.
Magic that fails strangely. An annotation on a method called from inside its own class does nothing, because the proxy is bypassed. That behavior has nothing to do with the injection itself, but it comes with the container.
Interfaces for everything. Teams create an interface per class "for DI". You only need one where there is more than one implementation or a boundary you want to fake. A concrete class injected by type works as well.
The principle behind the interfaces, depending on abstractions you own, is explored in dependency inversion beyond the slogan.
When you do not need a container
A command-line tool, a small batch job or a library should usually wire by hand. If the whole object graph fits in a screen of main, a container adds startup time and a learning curve for no gain. Libraries in particular should accept their collaborators through constructors and not depend on any container, so users of any framework can wire them. Reach for Spring when the graph is large, when you need scopes, transactions or proxies the container provides, or when the rest of your stack already assumes it. The API-level details are in the Javadoc, but the idea fits in one sentence: receive your parts, do not build them.


