NoUniqueBeanDefinitionException Spring Boot

In Spring's Dependency Injection, the NoUniqueBeanDefinitionException is a common exception developers encounter. In this article, we will dive into what this exception is, its primary causes, and how to address them. 

What is NoUniqueBeanDefinitionException? 

The NoUniqueBeanDefinitionException is thrown when the Spring container finds more than one bean of the same type and is unsure which one to inject. This ambiguity arises in the context of autowiring by type. 

Here's a typical error message you might see:

org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type '[SomeType]' available: 
expected single matching bean but found 2: [beanName1, beanName2]

How to Reproduce the Issue and Fix this issue

Reproduce: Multiple Beans of the Same Type

1. Create a simple interface and two implementations:
public interface Animal {
    String sound();
}

@Component
public class Dog implements Animal {
    @Override
    public String sound() {
        return "Woof!";
    }
}

@Component
public class Cat implements Animal {
    @Override
    public String sound() {
        return "Meow!";
    }
}
We have two beans (Dog and Cat) that implement the Animal interface. Both of these beans are managed by Spring, thanks to the @Component annotation.

2. Attempt to inject the Animal type:
@Component
public class AnimalService {

    private final Animal animal;

    @Autowired
    public AnimalService(Animal animal) {
        this.animal = animal;
    }

    public void makeSound() {
        System.out.println(animal.sound());
    }
}
In the AnimalService class, we have a constructor that requires an Animal type. When Spring tries to create a bean for AnimalService, it sees that there are two possible beans (Dog and Cat) that can be injected for the Animal type. This ambiguity causes the NoUniqueBeanDefinitionException.
org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type 'com.example.springboot.demo.Animal' available: 
expected single matching bean but found 2: cat,dog

How to Fix

Using @Qualifier Annotation: If you want to specify which exact bean to be injected, you can use the @Qualifier annotation:
@Autowired
public AnimalService(@Qualifier("cat") Animal animal) {
    this.animal = animal;
}
With this change, the Cat bean will be injected into the AnimalService class.

Using @Primary Annotation: If you want one of the beans to be the primary choice when injecting, you can use the @Primary annotation:
@Component
@Primary
public class Dog implements Animal {
    //...
}
With the above change, Dog will be the primary bean to be injected whenever an Animal type is required unless specified otherwise.

Other Common Causes & Solutions

Accidental Bean Overriding

Cause: Sometimes, multiple configurations or component scans could lead to beans being unintentionally overridden or duplicated. 

Solution: Review your configurations and component scans. Ensure there's no unintended overriding or duplication of bean definitions.

External Libraries with Bean Definitions

Cause: Sometimes, external libraries or modules you include might define beans of their own. If these bean types match with the ones in your application, ambiguity arises. 

Solution: Use the @Qualifier annotation to specify the exact bean name you want to inject. If you have control over the library, you can also modify the bean definitions to ensure uniqueness. 

Profiles

Cause: Different beans of the same type can be associated with different Spring profiles. 

Solution: Ensure that only one of the beans is active for the current profile. If multiple profiles are active, consider restructuring your beans or using the @Qualifier annotation for clarity. 

Conclusion

The NoUniqueBeanDefinitionException error in Spring signifies ambiguity in the dependency injection process. Resolving this typically involves being explicit about your intentions, either by specifying which bean you want to use or by ensuring that there's only one suitable candidate in the context. Always remember that clarity in configuration helps keep such issues at bay.

Related Spring Exceptions Posts

Comments