Sobes.tech
Senior

What are the purposes of @Qualifier and @Primary annotations in Spring?

sobes.tech AI

Answer from AI

In Spring, the annotations @Qualifier and @Primary are used to resolve ambiguities when injecting dependencies, especially when multiple beans of the same type exist in the context.

  • @Primary marks a bean as the primary one. If there are several candidates, Spring will choose the bean with this annotation by default.

  • @Qualifier allows explicitly specifying which bean to inject, using a name or a special identifier.

Example:

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

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

@Component
public class Consumer {
    private final MyService myService;

    // Injection using @Qualifier
    public Consumer(@Qualifier("specialService") MyService myService) {
        this.myService = myService;
    }
}

Thus, @Primary simplifies the default bean selection, while @Qualifier provides precise control when choosing a specific bean.