Sobes.tech
Middle

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

sobes.tech AI

Answer from AI

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

  • @Primary — marks a bean as the primary one, which will be injected by default if no other choice is specified.
  • @Qualifier — allows explicitly specifying which bean to inject, using a name or a special identifier.

Example:

@Component
@Primary
public class ServiceA implements MyService {}

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

// Injection
@Autowired
private MyService myService; // will get ServiceA, as it is @Primary

@Autowired
@Qualifier("specialService")
private MyService specialService; // will get ServiceB

Thus, @Primary sets the default bean, while @Qualifier allows selecting a specific bean when needed.