How to resolve NoSuchBeanDefinitionException: No qualifying bean of type available exception when using spring framework with autowire
Problem
When we run a Spring application with autowire injection, sometimes, this error would occur:
Spring framework is complaining that there should be a bean named CustomAuthentionProvider, but it cannot find it.
Environment
- SpringBoot 1.x and 2.x
The Codes
Let’s check the source code of CustomAuthentionProvider
:
It’s a normal class that implements an interface from Spring Security.
Let’s check the source code of the class that utilizes the CustomAuthentionProvider
:
You can see that the WebSecurityConfig class injected the class CustomAuthentionProvider by using the @Autowired
annotation, but why does it not work?
Solution
When we encounter the org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type xxxx available
, we should consider whether there is a Spring bean named xxx
in the runtime.
Spring Framework provides three ways to configure beans to be used in the application:
- Annotation Based Configuration – By using
@Service
or@Component
annotations. Scope details can be provided with@Scope
annotation. - XML Based Configuration – By creating a Spring Configuration XML file to configure the beans. If you are using Spring MVC framework, the XML-based configuration can be loaded automatically by writing some boilerplate code in
web.xml
. - Java Based Configuration – Starting from Spring 3.0, we can configure Spring beans using Java programs. Some important annotations used for Java-based configuration are
@Configuration
,@ComponentScan
, and@Bean
.
Now we can choose the first Annotation Based Configuration, which is the most convenient way to define or create Spring beans.
Look at the code:
The most important line of the code is:
The @Component
annotation creates a bean named CustomAuthentionProvider
in the Spring context.
Rerun the code, and the error disappears. It works!
Summary
In this post, we explored how to resolve the NoSuchBeanDefinitionException
in Spring Boot applications. The key takeaway is to ensure that the class you are trying to autowire is properly annotated with @Component
(or other stereotype annotations like @Service
or @Repository
). This ensures that the Spring IoC container can manage the bean and inject it where needed. By following the annotation-based configuration approach, you can avoid common pitfalls related to bean definition and autowiring.
Final Words + More Resources
My intention with this article was to help others who might be considering solving such a problem. So I hope that’s been the case here. If you still have any questions, don’t hesitate to ask me by email: Email me
Here are also the most important links from this article along with some further resources that will help you in this scope:
Oh, and if you found these resources useful, don’t forget to support me by starring the repo on GitHub!