Sub topic 1
Inversion of control: who creates your objects?
Prerequisites
This chapter assumes you know:
- Core Java: classes, interfaces, constructors and annotations.
- Basic object-oriented design, especially coupling and composition.
- How to build a project with Maven or Gradle.
You don't need to know Spring yet. This chapter explains the idea Spring is built on.
Who is in control?
In plain Java, a class that needs a collaborator usually creates it with new. The class decides which implementation it uses, when it is created, and how long it lives. That is normal control flow.
Inversion of control (IoC) reverses this. The class stops creating its collaborators and receives them from outside. Something else decides which implementation to use and when to create it. In Spring, that something is the container, which later chapters cover.
The problem with `new`
Here is a service that creates its own dependency:
public interface MessageSender {
void send(String to, String body);
}
public class EmailSender implements MessageSender {
@Override
public void send(String to, String body) {
System.out.println("email to " + to + ": " + body);
}
}
public class NotificationService {
private final MessageSender sender = new EmailSender();
public void welcome(String user) {
sender.send(user, "Welcome!");
}
}NotificationService is tied to EmailSender, even though its field is typed as the interface. This causes three problems:
- You can't switch to SMS without editing the service.
- A unit test can't replace the sender with a fake, so every test sends real email.
- If
EmailSenderlater needs a host name or credentials, every class that callsnew EmailSender()must supply them.
Inverting the control
The fix is to take the creation out of the class. The service declares what it needs and lets the caller supply it:
public class NotificationService {
private final MessageSender sender;
public NotificationService(MessageSender sender) {
this.sender = sender;
}
public void welcome(String user) {
sender.send(user, "Welcome!");
}
}
public class Main {
public static void main(String[] args) {
MessageSender sender = new EmailSender();
NotificationService service = new NotificationService(sender);
service.welcome("ana");
}
}NotificationService now knows only the MessageSender interface. The main method chose EmailSender and passed it in. Control over object creation moved from the service to its caller.
IoC is the principle, DI is the technique
Inversion of control is a general principle. Frameworks that call your code instead of you calling them also invert control, as with a web framework that invokes your handler method. Dependency injection (DI) is one technique for IoC. It applies the principle to object creation: dependencies are handed to an object instead of being fetched or built by it.
The main method above is a hand-written assembler. In a real application, that wiring code grows to dozens or hundreds of objects, each with its own dependencies, and you must create them in the right order. Spring takes over this job.
What the container does
A Spring container does the following:
- It reads a description of your objects, either annotations on classes or Java configuration.
- It works out which objects depend on which.
- It creates them in a valid order and passes each one its dependencies.
- It manages their lifetime, including cleanup at shutdown.
Your classes contain no lookup code and no new for collaborators. They only declare what they need.
Common mistakes
- Treating IoC and DI as synonyms. DI is one way to achieve IoC.
- Injecting a concrete class. If the constructor asks for
EmailSenderinstead ofMessageSender, the coupling is still there. - Still calling
newinside the class. Creating a collaborator in a method defeats the inversion, and the container can't help you there.
Exercise
A class has the field private final MessageSender sender = new EmailSender();. Name two problems this causes, and say what change moves control out of the class.
Show answer
The class is hard-wired to EmailSender, so switching implementations means editing the class. Tests also can't substitute a fake sender. To invert control, remove the new and accept a MessageSender through the constructor. The caller, or a container such as Spring, then chooses and supplies the implementation.