Sub topic 2
Dependency injection and why it reduces coupling
This chapter assumes you know Java classes, interfaces, constructors and annotations. It also assumes you have seen the idea of inversion of control from the previous chapter: the framework, not your code, decides when objects are created.
What a dependency is
A dependency is any object a class needs in order to do its work. If NotificationService sends messages through a sender, the sender is its dependency.
Dependency injection (DI) is the technique where a class receives its dependencies from the outside instead of creating them. It is the most common way to apply inversion of control.
The problem: a class that builds its own dependencies
Here is a service that creates its own sender.
public class SmtpEmailSender {
public void send(String to, String body) {
System.out.println("smtp to " + to + ": " + body);
}
}
public class NotificationService {
private final SmtpEmailSender sender = new SmtpEmailSender();
public void welcome(String user) {
sender.send(user, "Welcome!");
}
}This works, but NotificationService is tightly coupled to SmtpEmailSender. Coupling means one class cannot change or be used without the other. This code has three concrete problems:
- Switching to SMS means editing
NotificationService. - A test cannot replace the sender, so every test sends through the real implementation.
- The service must know how to construct its collaborator. If
SmtpEmailSenderlater needs a host and a port, every class that creates one must change.
The fix: depend on an interface and receive it
Define the capability as an interface. Then let the class declare what it needs as a constructor parameter.
public interface MessageSender {
void send(String to, String body);
}
@Service
public class NotificationService {
private final MessageSender sender;
// With a single constructor, @Autowired is optional.
public NotificationService(MessageSender sender) {
this.sender = sender;
}
public void welcome(String user) {
sender.send(user, "Welcome!");
}
}NotificationService now knows only the MessageSender contract. It does not know which implementation it gets, how that implementation was built, or how long it lives. Spring looks at the constructor, finds a bean of type MessageSender, and passes it in.
The diagram below shows the dependency direction after the change.
Why coupling goes down
Compare what changes in each design.
| Change | Self-built dependency | Injected dependency |
|---|---|---|
| Switch email to SMS | Edit `NotificationService` | Register a different bean |
| Add a constructor argument to the sender | Edit every class that creates it | Edit only the sender's definition |
| Test without real sending | Hard, needs hacks | Pass a fake |
The service no longer controls which implementation it uses. That decision moves to one place, the configuration that defines your beans. The next chapters cover how beans are defined and how Spring finds them.
Testing falls out for free
Because the dependency arrives through the constructor, a plain Java test can supply a fake. No Spring container is needed.
import java.util.ArrayList;
import java.util.List;
class NotificationServiceTest {
void welcomeSendsMessage() {
List<String> sent = new ArrayList<>();
NotificationService service =
new NotificationService((to, body) -> sent.add(to + ":" + body));
service.welcome("ana");
// sent now contains "ana:Welcome!"
}
}The lambda works because MessageSender has a single abstract method.
Common mistakes
- Injecting a concrete class instead of an interface. The class compiles, but you lose most of the flexibility.
- Using
newinside a bean for a collaborator. That collaborator is invisible to Spring and cannot be replaced or tested easily. - Treating DI as a goal on its own. Simple value objects and utilities with no behavior to swap do not need to be injected.
Exercise
A class ReportService contains the line private final PdfExporter exporter = new PdfExporter();. Name two problems with it and describe how you would change it.
Show answer
It is tightly coupled to PdfExporter, so you cannot switch to another format without editing ReportService, and a test cannot replace the exporter with a fake. Extract an Exporter interface that PdfExporter implements. Give ReportService a constructor parameter of type Exporter and assign it to a final field, so Spring or a test supplies the implementation.