Sobes.tech
Junior — Middle

How to select and implement a specific interface implementation in a Spring environment?

sobes.tech AI

Answer from AI

In Spring, the mechanism of dependency injection is usually used to select and inject a specific implementation of an interface. If you have multiple implementations of the same interface, you can choose the needed one using annotations or configuration.

Methods of selecting an implementation:

  1. @Qualifier — specify the exact bean name to inject the desired implementation.
public interface PaymentService {
    void pay();
}

@Service("paypalService")
public class PaypalPaymentService implements PaymentService {
    public void pay() { /* implementation */ }
}

@Service("stripeService")
public class StripePaymentService implements PaymentService {
    public void pay() { /* different implementation */ }
}

@Component
public class OrderProcessor {
    private final PaymentService paymentService;

    public OrderProcessor(@Qualifier("paypalService") PaymentService paymentService) {
        this.paymentService = paymentService;
    }
}
  1. @Primary — mark one implementation as the primary one, which will be injected by default.
@Service
@Primary
public class PaypalPaymentService implements PaymentService { ... }

@Service
public class StripePaymentService implements PaymentService { ... }
  1. Configuration via Java Config — explicitly create the bean of the required implementation.

  2. Spring Profiles (@Profile) — activate different implementations for different environments.

Thus, injecting a specific implementation boils down to correct annotation and bean configuration in the Spring context.

How to select and implement a specific interface… - sobes.tech