org.springframework. beans.factory. NoSuchBeanDefinitionException Solution

(105 Views)


In this article, we are discussing the Spring org.springframework.beans. factory.NoSuchBeanDefinitionException this is a common exception thrown by the BeanFactory when trying to resolve a bean that isn't defined in the current Spring Context.

We'll illustrate the possible causes for this problem and the available solutions.

      

Cause Of Exception:

Cause: No qualifying bean of type [?] found for dependency

The most common cause of this exception is simply trying to inject a bean that isn't defined. For example BeanQ is wiring in a collaborator BeanP:

Have a look at this Code snippet

@Component public class BeanP { @Autowired private BeanQ beanq; //... }

Now, if any dependency BeanP is not defined in the Spring Context, the container process will fail with the no such bean definition exception:

org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.packageQ.BeanQ] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}

Cause of this Exception:

We can see the reason of this exception, which is clearly indicated by Spring container: "expected at least 1 bean which qualifies as autowire candidate for this dependency"

One reason BeanQ may not exist in the spring container if beans are picked up automatically by classpath scanning, and if BeanQ is correctly annotated as a bean (@Component, @Repository, @Service, @Controller, etc) then other issue may be that BeanQ is defined in a package that is not scanned by Spring:

package com.packageQ.BeanQ; @Component public class BeanQ { //some code }

There might be the chances that classpath scanning may be configured as follows:

@Configuration @ComponentScan("com.packageP.BeanP") public class SpringAppJavaConfig { //some code }

If beans are not automatically scanned, then BeanQ is simply not defined in the current Spring Container.

Solution

Just change the Package scanning to Root package so that all the beans are scanned by Spring.

@Configuration @ComponentScan("com")//defining here root package public class ContextJavaConfig { //some logic }

If you have any other doubt, feel free to ask us in the comments section, we will try to solve it too.

Solution Worked 0 UpvotesUpvote

        

Solution Didn't Worked 0 DownvotesDownvote



Comments



Search