The Master Class of "Learn Spring Security" is out:

>> CHECK OUT THE COURSE

1. Overview

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 simply isn’t defined in the Spring Context.

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

And of course, exceptions happen when you least expect them; have a look at the full list of exceptions and solutions in Spring.

2. 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 – BeanB is wiring in a collaborator – BeanA: 

@Component
public class BeanA {

    @Autowired
    private BeanB dependency;
    ...
}

Now, if the dependency – BeanB – is not defined in the Spring Context, the bootstrap process will fail with the no such bean definition exception:

org.springframework.beans.factory.NoSuchBeanDefinitionException: 
    No qualifying bean of type [org.baeldung.packageB.BeanB] found for dependency: 
    expected at least 1 bean which qualifies as autowire candidate for this dependency. 
    Dependency annotations: [email protected](required=true)}

The reason is clearly indicated by Spring: “expected at least 1 bean which qualifies as autowire candidate for this dependency

One reason BeanB may not exist in the context – if beans are picked up automatically by classpath scanning, and if BeanB is correctly annotated as a bean (@Component, @Repository, @Service, @Controller, etc) – is that it may be defined in a package that is not scanned by Spring:

package org.baeldung.packageB;
@Component
public class BeanB { ...}

While the classpath scanning may be configured as follows:

@Configuration
@ComponentScan("org.baeldung.packageA")
public class ContextWithJavaConfig {
    ...
}

If beans are not automatically scanned by instead defined manually, then BeanB is simply not defined in the current Spring Context.

3. Cause: No qualifying bean of type […] is defined

Another cause for the exception is the existence of two bean definitions in the context, instead of one. For example, if an interface – IBeanB is implemented by two beans – BeanB1 and BeanB2:

@Component
public class BeanB1 implements IBeanB {
    //
}
@Component
public class BeanB2 implements IBeanB {
    //
}

Now, if BeanA autowires this interface, Spring will not know which one of the two implementations to inject:

@Component
public class BeanA {

    @Autowired
    private IBeanB dependency;
    ...
}

And again, this will result in a NoSuchBeanDefinitionException being thrown by the BeanFactory:

Caused by: org.springframework.beans.factory.NoUniqueBeanDefinitionException: 
No qualifying bean of type [org.baeldung.packageB.IBeanB] is defined: 
expected single matching bean but found 2: beanB1,beanB2

Similarly, Spring clearly indicates the reason for the wiring failure: “expected single matching bean but found 2”.

Notice however, that in this case, the exact exception being thrown is not NoSuchBeanDefinitionException but a subclass – the NoUniqueBeanDefinitionException. This new exception has been introduced in Spring 3.2.1, for exactly this reason – to differentiate between the cause where no bean definition was found and this one – where several definitions are found in the context.

Before this change, the exception above was:

Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: 
No qualifying bean of type [org.baeldung.packageB.IBeanB] is defined: 
expected single matching bean but found 2: beanB1,beanB2

One solution to this problem is to use the @Qualifier annotation to specify exactly the name of the bean we want to wire:

@Component
public class BeanA {

    @Autowired
    @Qualifier("beanB2")
    private IBeanB dependency;
    ...
}

Now Spring has enough  information to make the decision of which bean to inject – BeanB1 or BeanB2 (the default name of BeanB2 is beanB2).

4. Cause: No Bean Named […] is defined

A NoSuchBeanDefinitionException may also be thrown when a bean that isn’t defined is requested by name from the Spring context:

@Component
public class BeanA implements InitializingBean {

    @Autowired
    private ApplicationContext context;

    @Override
    public void afterPropertiesSet() {
        context.getBean("someBeanName");
    }
}

In this case, there is no bean definition for “someBeanName” – leading to the following exception:

Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: 
No bean named 'someBeanName' is defined

Again, Spring clearly and concisely indicates the reason for the failure: “No bean named X is defined“.

5. Cause: Proxied Beans

When a bean in the context is proxied using the JDK Dynamic Proxy mechanism, then the proxy will not extend the target bean (it will however implement the same interfaces).

Because of this, if the bean is injected by an interface, it will be correctly wired in. If however the bean is injected by the actual class, then Spring will not find a bean definition that matches the class – since the proxy does not actually extend the class.

A very common reason the bean may be proxied is the Spring transactional support – namely beans that are annotated with @Transactional.

For example, if ServiceA injects ServiceB, and both services are transactional, injecting by the class definition will not work:

@Service
@Transactional
public class ServiceA implements IServiceA{

    @Autowired
    private ServiceB serviceB;
    ...
}

@Service
@Transactional
public class ServiceB implements IServiceB{
    ...
}

The same two services, this time correctly injecting by the interface, will be OK:

@Service
@Transactional
public class ServiceA implements IServiceA{

    @Autowired
    private IServiceB serviceB;
    ...
}

@Service
@Transactional
public class ServiceB implements IServiceB{
    ...
}

6. Conclusion

This tutorial discussed examples of the possible causes for the common NoSuchBeanDefinitionException – with a focus on how to address these exceptions in practice.

The implementation of all these exceptions examples can be found in the github project – this is an Eclipse based project, so it should be easy to import and run as it is.

Finally, the full list of exceptions and solutions in Spring might be a good resource to bookmark.

The Master Class of "Learn Spring Security" is out:

>> CHECK OUT THE COURSE

  • Irina

    Thank you for this article! You saved my day with point five! =)

  • pali

    Thanks a lot! It saved my problem, and helped to understand things… Wish I found this article three hours ago… 🙂

  • Alex Spence

    THANK YOU. So much time wasted trying to figure this out. This is the only article I could find that actually helped me.

    • Cool, I was wondering if an exception focused article is going to be helpful or not – I’m glad it is. Cheers,
      Eugen.

  • PA

    In case of Spring Batch and spring-mongo-data integration, it looks like we can’t use repository classes, it’s says

    org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘scopedTarget.memberProcessor’: Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.test.google.repository.StudentDetailsRepository com.test.google.processor.StudentDetailsProcessor.studentRepo; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.test.google.repository.StudentDetailsRepository] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: [email protected](required=true)}

    Could you please help/guide me?

  • jothi manickam

    Hi i am getting below exception
    org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name ‘loginDaoImpl’: Unsatisfied dependency expressed through field ‘loginService’: Error creating bean with name ‘loginService’: Unsatisfied dependency expressed through field ‘userRepository’: No qualifying bean of type [com.demo.repository.UserRepository] found for dependency [com.demo.repository.UserRepository]: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: [email protected](required=true)}; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.demo.repository.UserRepository] found for dependency [com.demo.repository.UserRepository]: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: [email protected](required=true)}; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name ‘loginService’: Unsatisfied dependency expressed through field ‘userRepository’: No qualifying bean of type [com.demo.repository.UserRepository] found for dependency [com.demo.repository.UserRepository]: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: [email protected](required=true)}; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.demo.repository.UserRepository] found for dependency [com.demo.repository.UserRepository]: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: [email protected](required=true)}

    please help me to resolve this

    • Well Jothi – it simply looks like your configuration isn’t picking up the the user repository as a bean. You can either define the bean manually, scan it in by package or, if it’s a Spring Data JPA bean – point to the package where these repositories are located in your configuration.
      Also, can you please edit your commend and remove the initial part of the execption, and just leave the NoSuchBeanDefinitionException in there?
      Hope that helps. Cheers,
      Eugen.

      • Prash

        manually assigned the bean as well but still getting this Error.

        • Well Prash – at this point it’s no something I can debug without looking at code. Feel free to email me the details. Cheers,
          Eugen.

  • Hey Peter – good point.

  • Mahalaxmi Sanathkumar

    I have a situation where- my bean’s interface is in package com.a and its implementation is in com.b. Now even if I used a component scan for both packages. I still end up with NoSuchBeanDefinitionException. Any pointers?

    • Grzegorz Piwowarek

      Component scanning picks up everything in a package. So, in this case, there is no use in adding another one. It’s very hard to answer your question. If you post your code on GitHub, I could have a look and investigate

  • Grimbo

    I am facing also a “No qualifying bean of type […] is defined” error. Full description can be found at Stackoverflow: http://stackoverflow.com/questions/40281151/no-qualifying-bean-of-type-myowntype-primitive-beans-like-string-works

    I am still looking forward to find a solution!

    • Grzegorz Piwowarek

      Ok, I had a look and the first thing that was shocking for me is that you managed to combine multiple Spring mechanisms in order to try to define a bean. This is undebuggable in such a form.

      Let’s start by getting rid of ComponentScan on the config class and getting rid of @Service annotation from the bean. Those mechanisms interfere with each other and are causing problems. Also, you have a typo in the ComponentScan.

      Why not just @Autowire this bean as any other?

      • Grimbo

        Well you fixed it! Typo comes from not using copy-paste. But since I deleted @Service and @ComponentScan I can finally load the bean and return the instance.

        So my questions are now:
        1. When is @ComponentScan necessary? And when should I avoid using it?
        2. When is @Service or @Component necessary? And when should I avoid it?
        3. I am pretty new in Spring and is it possible to autowire beans from other services?
        4. Can you recommend me a site, tutorial, book, etc. which also could answered my question? And also to improve my knowledge?

        Thx a lot so far!
        G.

        • Grzegorz Piwowarek

          http://www.baeldung.com/spring-bean-annotations This resource should help you a lot in understanding the first two.
          3. I am not really sure what do you mean “autowire beans from other services”. By default, beans are singleton-scoped so whenever you are autowiring something it’s the same instance that gets autowired so it never actually “belongs” to anything
          4. Well, baeldung 🙂 Read this one too: http://www.baeldung.com/spring-autowire
          If you are missing some info, let us know and we will simple enhance those articles. Cheers!

          • Grimbo

            So I hope I got it right. If I am using @Component, @Repository, @Service, @Controller somewhere in my project and all beans are located in my @Configuration I do not need a specific “component scan” to told Spring where to find my components. @ComponentScan is only needed when I want to declare beans outside my configuration class or?

          • Grzegorz Piwowarek

            If you annotate a class with (@Service, @Component, @Controller, @Repository), Spring will create singleton-scoped beans from them automatically. In @Configuration-annotated class, you can use @Bean-annotated methods where beans will be created from a return result. @ComponentScan can specify packages that Spring traverses in search for possible beans so if your @Configuration-annotated class depends on beans that get created outside the current package hierarchy, you might want to specify this package explicitly with @ComponentScan. It’s really hard to write all Spring basics in a few words but I hope it helps anyway 🙂

          • Grimbo

            Thank your for your help and detailed answers!

          • Grzegorz Piwowarek

            You are welcome 🙂