Success means your Spring context starts without ambiguity and each injection point gets the bean you intend. You can achieve this in under 10 minutes by using qualifiers, primary markers, or named beans. The steps below cover the three standard approaches and when to use each.
Before You Start: What You Need
- A Spring project (Boot or plain) with at least two beans of the same type.
- Access to the configuration class or XML file where beans are declared.
- Knowledge of which bean should be the default (if any) and which injection points need a specific one.
Step 1: Identify the Ambiguity
When Spring finds multiple beans of the same type and no other hint, it throws NoUniqueBeanDefinitionException. The error message lists the candidate beans. Read that list to know exactly which beans are competing.
Step 2: Use @Primary for a Default Bean
If one bean should be used by default at most injection points, mark it with @Primary. Spring will choose it whenever no qualifier is specified.
- Add
@Primaryto the bean definition (on the class or the@Beanmethod). - Keep other beans unmarked.
- Inject without any qualifier to get the primary bean.
Example: @Bean @Primary public DataSource primaryDataSource() { ... }
Step 3: Use @Qualifier for Specific Injection
When an injection point needs a non-primary bean, or when you want to be explicit, use @Qualifier with a bean name or a custom qualifier annotation.
- Give each bean a name (either the method name or the
@Qualifiervalue). - At the injection point, add
@Qualifier("beanName")before the field, constructor parameter, or setter. - Spring will match the qualifier value to the bean name or qualifier annotation.
Example: @Autowired @Qualifier("secondary") private DataSource dataSource;
Step 4: Use @Resource for Name-Based Lookup (JSR-250)
If you prefer a standard Java annotation, @Resource (from javax.annotation or jakarta.annotation) matches by bean name first, then by type.
- Add
@Resource(name = "beanName")to the field or setter. - If no name is given, Spring uses the field name as the bean name.
Example: @Resource(name = "primaryDataSource") private DataSource dataSource;
Step 5: Combine @Primary and @Qualifier When Needed
You can use both together. The primary bean is the fallback; qualifiers override it at specific points. This is common when you have a default implementation and an alternative (e.g., a test or a special environment).
- Mark one bean as
@Primary. - Add
@Qualifierat injection points that need the other bean.
What If the Beans Are in a List or Map?
Spring can inject a List or Map of all beans of a type. This is useful for plugins or strategies.
- Inject
List<MyType>to get all beans in order of definition. - Inject
Map<String, MyType>to get beans keyed by their bean name.
This avoids ambiguity entirely because you are asking for all of them.
Common Errors and Fixes
| Symptom | Cause | Fix |
|---|---|---|
NoUniqueBeanDefinitionException at startup |
Multiple beans, no primary, no qualifier | Add @Primary or @Qualifier at the injection point |
| Wrong bean injected (silently) | Qualifier value does not match any bean name | Check the bean name (method name or @Qualifier value) and correct it |
NoSuchBeanDefinitionException after adding qualifier |
Typo in qualifier or the bean is not registered | Verify the bean name in the configuration and the qualifier spelling |
Which Approach Should You Use?
Use @Primary when there is a clear default. Use @Qualifier when you need to pick a specific bean at a particular injection point. Use @Resource if you are already using JSR-250 annotations. For a collection of beans, inject a List or Map.
Does This Work With Constructor Injection?
Yes. For constructor injection, place @Qualifier on the parameter:
public MyService(@Qualifier("secondary") DataSource dataSource) { ... }
If you have multiple parameters, each can have its own qualifier.
What About XML Configuration?
In XML, use primary="true" on the <bean> element for the default, and <qualifier value="beanName"/> inside the bean definition for qualifiers. At injection points, use <constructor-arg> or <property> with qualifier attribute.
Handling Multiple Beans in Tests
In unit tests, you can use @MockBean or @TestConfiguration to override specific beans. For integration tests, you can define a test configuration with @Primary beans. The same qualifier rules apply.
What If Two Beans Have the Same Name?
Bean names must be unique within a Spring context. If you try to define two beans with the same name, the second definition overrides the first (unless you set allowBeanDefinitionOverriding to false). Always give distinct names to avoid confusion.
With these steps, you can resolve any multiple-bean ambiguity in a few minutes. Start by reading the exception message, then apply the appropriate annotation. Test your configuration after each change to confirm the right bean is injected.
Related
- Cake Carrier with Handle Kmart: What to Know
- Cake Text Symbol: How to Type and Use It
- Tupperware Cake Carrier Replacement Handle
Safe minimum internal temperatures follow USDA FSIS; raw-fish guidance follows the U.S. FDA. See our food safety notes.
Spotted an error? Tell us and we will correct it (corrections policy).