Video in progress
What is a Service Locator and why is it worse than Dependency Injection?
With a Service Locator, a class asks a central registry for the dependency it needs (context.getBean(...)). It works, but the dependencies aren't visible in the constructor, tests have to set up the registry, and errors only show up at runtime.
📖 Answer
@Service
class ReportService {
@Autowired private ApplicationContext ctx;
public byte[] export(String format) {
var exporter = ctx.getBean(format + "Exporter", Exporter.class); // locator
var repo = ctx.getBean(ReportRepository.class);
return exporter.export(repo.load());
}
}
Problems:
- you only learn which beans the class depends on by reading its internals;
- in a test you can't just do
new ReportService(): you need the whole context or a mockApplicationContext; - if the bean name
"pdfExporter"is misspelled,NoSuchBeanDefinitionExceptiononly shows up when that branch runs; - the code gets tied to the Spring API.
The DI version, with the same dynamic choice:
@Service
class ReportService {
private final Map<String, Exporter> exporters; // bean name -> bean
private final ReportRepository repo;
ReportService(Map<String, Exporter> exporters, ReportRepository repo) { ... }
public byte[] export(String format) {
var e = exporters.get(format + "Exporter");
if (e == null) throw new UnsupportedFormatException(format);
return e.export(repo.load());
}
}
The dependencies are visible, and a test just passes a plain Map.of(...).
Places where a locator is fine: framework infrastructure, getting a lazy or prototype bean through ObjectProvider<T>, loading plugins with ServiceLoader. If you see getBean in business code, it's a sign someone is bypassing DI.
Sign up to mark studied questions and save your progress.