Sobes.tech
Senior

What are the @Qualifier and @Primary annotations used for?

sobes.tech AI

Answer from AI

The @Qualifier and @Primary annotations in Spring are used to control the selection of a bean during dependency injection when there are multiple candidates of the same type in the context.

  • @Primary marks a bean as the preferred one if there are multiple beans of the same type and no @Qualifier is specified. During autowiring, Spring will choose the bean with @Primary by default.

  • @Qualifier allows explicitly specifying which bean to use by assigning a unique name or value. This is useful when you need to select a specific bean among several, even if there is a @Primary.

Example:

@Component
@Primary
public class ServiceA implements MyService {
    // implementation
}

@Component
@Qualifier("serviceB")
public class ServiceB implements MyService {
    // different implementation
}

@Component
public class Client {
    private final MyService myService;

    // ServiceA is injected because it is @Primary
    public Client(MyService myService) {
        this.myService = myService;
    }

    // Or explicitly specify the bean using @Qualifier
    @Autowired
    public Client(@Qualifier("serviceB") MyService myService) {
        this.myService = myService;
    }
}

Thus, @Primary sets the default bean, and @Qualifier allows precisely specifying the needed bean.

What are the @Qualifier and @Primary annotations used… - sobes.tech