NoUniqueBeanDefinitionException: No qualifying bean of type in spring, need of @Qualifier

The story will tell about the scenario of the application failed to start due to an exception org. spring framework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type.

I will explain the one scenario that happens. As described in the image we have class One that implements interface A and class Two extend class B and interface B.

I have one action, facade, or handler component class where I need to invoke for service for two different purposes.

As per HandlerClass uses the @Autowired
private InterfaceA interfaceA;

@Autowired
private Interfaceb interfaceB.

Here we will get the compile-time error like Could not autowire there is more than bean.

Reason

You have two classes marked as being Spring autowired components.

You can only have one active in the runtime code.

This normally happens to me when I have an interface and then have two implementations that I want to switch via config.

Autowire Conflict Resolution

By default, Spring resolves @Autowired entries byType. If more than one bean of the same type is available in the container, the framework will throw NoUniqueBeanDefinitionException an exception, indicating that more than one bean is available for autowiring

There are two simple ways you can resolve the NoUniqueBeanDefinitionException exception in Spring. You can use the

Solution

@Primary

annotation, which will tell Spring when all other things are equal to select the primary bean over other instances of that type for the autowire requirement.

The second way is to use the

@Qualifier

annotation. Through the use of this annotation, you can give Spring hints about the name of the bean you want to use. By default, the reference name of the bean is typically the lower case class name.

Java 8 | Spring | React | Angular | CI/CD | Microservices | Monitoring |Apache Kafka. https://www.linkedin.com/in/shuaib-kunhabdulla-83780188