Service Locator Injection (ARCH4198)
Ce contenu n’est pas encore disponible dans votre langue.
Key java.quality.service-locator · Severity warning · Category quality
Injecting the container/provider and resolving services from it at runtime hides dependencies and hurts testability. Take dependencies via constructor injection instead.
Incorrect
Section titled “Incorrect”@Serviceclass OrderService { private final ApplicationContext ctx; OrderService(ApplicationContext ctx) { this.ctx = ctx; }
void place() { ctx.getBean(PaymentGateway.class).charge(); }}Correct
Section titled “Correct”@Serviceclass OrderService { private final PaymentGateway gateway; OrderService(PaymentGateway gateway) { this.gateway = gateway; }
void place() { gateway.charge(); }}Inject the services you need directly as constructor parameters rather than the container.