Dependency injection
Dependency injection means an object receives its collaborators from outside instead of constructing them. You pass a Mailer into SignupService. Tests pass a fake. Production passes the real one.
Detailed Explanation
new SmtpMailer() inside SignupService couples the service to SMTP. You cannot test signup without a network. Injection inverts that: the service declares what it needs. A composer at the edge (main, a Spring context) builds the graph and passes objects in.
Constructor injection is the default in Java. Fields are final. The object is never half-wired. Setter injection allows optional collaborators and circular graphs; it also allows use-before-set. Field injection (@Autowired on a field) is short and hides the contract; avoid it in new code.
Spring, Guice, and CDI are containers that perform injection with annotations and proxies. You can inject by hand in a small app: new SignupService(new SmtpMailer()). The pattern is the passing, not the framework.
You reach for DI when a class has collaborators that vary (tests, environments) or that are expensive. You new value objects and DTOs directly. You do not inject String name of the user; that is data, not a dependency.
The cost of a huge constructor is a class that does too much (SOLID S). The cost of a container you do not understand is magic: proxies, circular dependencies, startup failures. Keep constructors honest. The cost of service locator (context.getBean) is hidden dependencies; prefer constructor parameters.
Circular injection (A needs B needs A) is a design smell. Break it with an event, a third type, or a setter you hate and document.
The composition root is allowed to be ugly. main or a @Configuration class may contain twenty new calls. That is better than twenty classes each constructing their own graph. Once the process is running, objects should not look up collaborators. If a method calls SpringContext.getBean, you have a service locator, and the constructor is lying about what the class needs.
Code Examples
interface Mailer {
void send(String to, String body);
}
class SignupService {
private final Mailer mailer;
SignupService(Mailer mailer) { // constructor injection
this.mailer = mailer;
}
void welcome(String email) {
mailer.send(email, "welcome");
}
public static void main(String[] args) {
Mailer log = (to, body) -> System.out.println(to + ":" + body);
new SignupService(log).welcome("a@b.com"); // prints: a@b.com:welcome
}
}Common Gotchas
Field injection hides required collaborators
use constructors so the compiler enforces them.