Video in progress
What's the difference between @Primary and @Qualifier, and which one wins if both are present?
@Primary is a general hint: "if there are several candidates, take this one". @Qualifier picks a specific bean at a specific injection point. When they clash, @Qualifier wins.
📖 Answer
@Bean @Primary
DataSource mainDataSource() { ... }
@Bean
DataSource reportingDataSource() { ... }
public UserRepositoryImpl(DataSource ds) { ... } // mainDataSource
public ReportDao(@Qualifier("reportingDataSource") DataSource ds) { ... } // picked explicitly
When to use which:
- one implementation is needed almost everywhere and the other rarely —
@Primary; - every injection point needs a deliberate choice —
@Qualifier.
String names are easy to get wrong: rename a bean and the compiler says nothing, the error only shows up at startup. That's why some teams write their own qualifier annotation:
@Qualifier @Retention(RUNTIME) @Target({FIELD, PARAMETER, METHOD, TYPE})
public @interface Reporting {}
Now it's @Reporting DataSource ds — safer when refactoring.
Sign up to mark studied questions and save your progress.