Video in progress

What is the difference between Service Locator and Dependency Injection? Why is calling `applicationContext.getBean()` everywhere a bad habit in Spring?

With a Service Locator, the class asks a central registry for what it needs; with DI, the dependencies are supplied from outside, usually through the constructor. With getBean() a class gets a hidden dependency and it's hard to swap in a test.

📖 Answer

// Service Locator
public class ReportJob {
    public void run() {
        var repo = SpringContext.getBean(SaleRepository.class);
        var mail = SpringContext.getBean(MailService.class);
        ...
    }
}

// DI
public class ReportJob {
    private final SaleRepository repo;
    private final MailService mail;
    public ReportJob(SaleRepository repo, MailService mail) { ... }
}

In the first version you can't tell from the class signature what it needs. In a test you have to start the whole Spring context or set up static state. If a bean isn't found, the error shows up not at startup but when run() is called, perhaps in a job that runs at night.

With DI, the dependencies are visible in the constructor, a test passes mocks with a plain new, and a missing bean fails while the application is starting up.

When a Service Locator is appropriate: when you need a bean inside an object that Spring doesn't manage (for example, a class created by an old library, or a JPA AttributeConverter in old versions). Or when you need to pick dynamically by name at runtime, but even then injecting a Map<String, T> or using ObjectProvider<T> is cleaner.