BackendBench
Coffee

Home โ€บ Java exceptions โ€บ NoUniqueBeanDefinitionException

Unchecked exception ยท org.springframework.beans.factory

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,reportingDs

Extends 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

How to fix it

  1. Mark one candidate with @Primary.
  2. Select explicitly at the injection point with @Qualifier("name").
  3. Inject a Map<String, Type> or List<Type> if you want all of them.
  4. Remove or conditionally disable the bean you do not need.

Broken and fixed

fails
@Autowired DataSource ds; // primaryDs and reportingDs both match
works
@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.

Related exceptions

More tools you might need