Home โบ Java exceptions โบ NoUniqueBeanDefinitionException
NoUniqueBeanDefinitionException: causes and fixes
More than one bean matches an injection point and Spring cannot choose between them.
What it looks like
org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type 'javax.sql.DataSource' available: expected single matching bean but found 2: primaryDs,reportingDsExtends NoSuchBeanDefinitionException in org.springframework.beans.factory.
What it means
Injection by type found several candidates. The message lists the bean names, which makes the cause obvious. Spring needs a rule to pick one: a primary bean, a qualifier, or an injection point whose parameter name matches the bean name. It often appears after adding a second DataSource, a second ObjectMapper or a second implementation of an interface.
Common causes
- Two or more implementations of the same interface registered as beans.
- A second
DataSource,RestTemplateorObjectMapperbean next to an auto-configured one. - A test configuration that defines a duplicate of a production bean.
- Component scanning picking up both an interface implementation and a subclass of it.
How to fix it
- Mark one candidate with
@Primary. - Select explicitly at the injection point with
@Qualifier("name"). - Inject a
Map<String, Type>orList<Type>if you want all of them. - Remove or conditionally disable the bean you do not need.
Broken and fixed
@Autowired DataSource ds; // primaryDs and reportingDs both match@Bean @Primary
DataSource primaryDs() { ... }
// or
@Autowired @Qualifier("reportingDs") DataSource ds;๐ Unravel the failing code ๐ Unravel the fix
In Spring and enterprise code
Adding a custom ObjectMapper bean disables Spring Boot's auto-configured one (it backs off), which can change JSON output across the app. Prefer customising with a Jackson2ObjectMapperBuilderCustomizer.
Debug it faster
Paste the whole stack trace into the stack trace beautifier to hide framework frames, jump to the root cause and find the first line of your own code. It runs in your browser, so the trace never leaves your machine.
Frequently asked questions
Is NoUniqueBeanDefinitionException a checked or unchecked exception?
NoUniqueBeanDefinitionException is an unchecked exception (it extends NoSuchBeanDefinitionException, which is a RuntimeException), so you are not forced to catch it. Prevent it with validation, or handle it where the input enters the system.
Which package is NoUniqueBeanDefinitionException in?
It lives in org.springframework.beans.factory, so the import is import org.springframework.beans.factory.NoUniqueBeanDefinitionException;.
What is the first thing to check when I see NoUniqueBeanDefinitionException?
Read the message and the first stack trace line in your own code. The usual causes are: Two or more implementations of the same interface registered as beans; and A second DataSource, RestTemplate or ObjectMapper bean next to an auto-configured one.