Sobes.tech
Junior — Middle

What is the role of the @Primary annotation in the Spring framework and when should it be used?

sobes.tech AI

Answer from AI

The @Primary annotation in Spring is used to specify the preferred bean when multiple candidates of the same type are available in the context. If Spring cannot unambiguously select a bean for injection due to multiple suitable options, the bean marked with @Primary will be chosen by default.

Use @Primary when:

  • There are multiple implementations of an interface or class.
  • You want to explicitly specify which bean to use by default.

Example:

@Component
@Primary
public class DefaultPaymentService implements PaymentService {
    // implementation
}

@Component
public class SpecialPaymentService implements PaymentService {
    // another implementation
}

In this case, when autowiring PaymentService, DefaultPaymentService will be selected unless specified otherwise.