Review narrow Java cases where Service Locator is defensible and where dependency injection or explicit composition is usually clearer.
Service Locator is easiest to evaluate through examples, because the difference between a justified lookup boundary and a hidden-dependency shortcut becomes obvious in context.
Suppose an application loads reporting exporters provided by modules:
At runtime, the application may discover which exporters are present and expose them by type or key. A locator-style registry can make sense here because runtime lookup is part of the actual extension model.
Older Java frameworks and application servers sometimes expose resources through central contexts or registries. When integrating with that infrastructure, a local Service Locator wrapper can isolate the legacy lookup API from the rest of the system.
That can be useful if the wrapper keeps the damage contained and the rest of the codebase still prefers explicit injection.
Sometimes an application may optionally provide an audit sink, tracing backend, or feature-specific adapter. Lookup can be acceptable if:
Even here, many teams prefer injecting an optional strategy or no-op implementation instead.
Service Locator is a poor fit when ordinary business classes retrieve their own collaborators:
1public final class CheckoutService {
2 private final ServiceLocator locator;
3
4 public CheckoutService(ServiceLocator locator) {
5 this.locator = locator;
6 }
7
8 public Receipt checkout(Cart cart) {
9 PaymentGateway gateway = locator.get(PaymentGateway.class);
10 InventoryService inventory = locator.get(InventoryService.class);
11 FraudPolicy fraudPolicy = locator.get(FraudPolicy.class);
12 // ...
13 }
14}
At that point, the constructor no longer tells the truth about what the service needs. The class is more difficult to test and easier to over-couple.
Before choosing Service Locator, compare it with:
Often the right answer is not “no central object at all,” but “a more precise central object.”
When reviewing a Java Service Locator use case, ask:
Service Locator becomes acceptable when lookup is the domain truth. It becomes harmful when lookup is simply convenient.