转http://www.baeldung.com/spring-nosuchbeandefinitionexception

1. Overview

In this article, we are discussing the Springorg.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 will discuss here the possible causes for this problem and the available solutions.

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:

1
2
3
4
5
6
7
@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:

1
2
3
4
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: {@org.springframework.beans.factory.annotation.Autowired(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 byclasspath 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:

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

While the classpath scanning may be configured as follows:

1
2
3
4
5
@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:

1
2
3
4
5
6
7
8
@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:

1
2
3
4
5
6
7
@Component
public class  BeanA {
 
    @Autowired
    private IBeanB dependency;
    ...
}

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

1
2
3
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 notNoSuchBeanDefinitionException but a subclass – theNoUniqueBeanDefinitionException. 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:

1
2
3
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:

1
2
3
4
5
6
7
8
@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 isrequested by name from the Spring context:

1
2
3
4
5
6
7
8
9
10
11
@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:

1
2
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:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
@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:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
@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 commonNoSuchBeanDefinitionException – 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.

Spring NoSuchBeanDefinitionException的更多相关文章

  1. Spring NoSuchBeanDefinitionException原因分析

    摘要:摘要:本文译自EugenParaschiv文章SpringNoSuchBeanDefinitionException原文链接:/2014th7cj/d/file/p/20161012/dv5o0 ...

  2. Spring NoSuchBeanDefinitionException六大原因总结

    1. Overview In this article, we are discussing the Springorg.springframework.beans.factory.NoSuchBea ...

  3. Atitit s2018 s4 doc list dvchomepc dvccompc.docx .docx \s2018 s4 doc compc dtS44 \s2018 s4 doc dvcCompc dtS420 \s2018 s4f doc homepc \s2018 s4 doc compc dtS44\(5 封私信 _ 44 条消息)WebSocket 有没有可能取代 AJAX

    Atitit s2018 s4 doc list dvchomepc dvccompc.docx .docx \s2018 s4 doc compc dtS44 \s2018 s4 doc dvcCo ...

  4. spring Boot异步操作报错误: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.self.spring.springboot.Jeep' available

    我也是最近开始学习Spring Boot,在执行异步操作的时候总是汇报如下的错误: Exception in thread "main" org.springframework.b ...

  5. Spring Boot 调用 MongoRepository时报org.springframework.beans.factory.NoSuchBeanDefinitionException错误的解决办法

    这个问题整整折腾了我两天,现在记录下来,希望可以帮助和我一样,遇到相同问题的小伙伴. 项目是分层的(Intellij IDEA中的模块Module),有API(Core)层,Service&D ...

  6. Spring报NoSuchBeanDefinitionException

    org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 上述可以看出Ac ...

  7. spring源码分析之freemarker整合

    FreeMarker是一款模板引擎: 即一种基于模板和要改变的数据, 并用来生成输出文本(HTML网页.电子邮件.配置文件.源代码等)的通用工具. 它不是面向最终用户的,而是一个Java类库,是一款程 ...

  8. [Spring]04_最小化Spring XML配置

    4.1 自动装配 Bean Spring 装配 bean 时,有时非常明确,就是需要将某个 bean 的引用装配给指定属性. 例如,若应用上下文中只有一个 javax.sql.DataSource 类 ...

  9. Spring中常见的bean创建异常

    Spring中常见的bean创建异常 1. 概述     本次我们将讨论在spring中BeanFactory创建bean实例时经常遇到的异常 org.springframework.beans.fa ...

随机推荐

  1. mysql之show engine innodb status解读(转)

    add by zhj: 我第一次知道这个命令是线上服务出了问题,然后同事用这个命令去查看死锁.但用这个命令看死锁有一定的局限性,它只能看到最后一次死锁, 而且只能看到死锁环中的两个事务所执行的最后一条 ...

  2. VSCode代码修改后跑起来没反应,打开本地文件,代码没变化

    两种解决办法: 首先:修改VSCode默认配置文件,点击左下角设置标志图 -> 设置,出来了设置相关的东西,搜索 files.autoSave 第一种:把"files.autoSave ...

  3. ntpdata 同步时间

    ntpdate用来同步时间 [root@localhost ~]# yum install -y ntp [root@localhost ~]# ntpdate time.windows.com # ...

  4. mysql数据库数据(字段数过大)太多导入不了的解决方法

    mysql数据库数据(字段数过大)太多导入不了的决方法: 1.打开navicat 工具 2.在数据库上右键,执行右键菜单命令“命令列界面” 3.在打开的窗口中,运行set global max_all ...

  5. 三角形的优雅值(map和哈希表)

    给你 n 个三角形,每个三角形有一个优雅值,然后给出一个询问,每次询问一个三角形,求与询问的三角形,相似的三角形中的优雅值最大是多少.★数据输入第一行输入包括 n 一个数字,接下来 n 行,每行四个整 ...

  6. MySQL大表优化方案 Mysql的row_format(fixed与dynamic)

    转自:https://mp.weixin.qq.com/s/VY69wWlrVLjRtKU7ULrYGw 当MySQL单表记录数过大时,增删改查性能都会急剧下降,可以参考以下步骤来优化: 单表优化 除 ...

  7. sap 申请 新系统用户

    1:打开sap  logon, 进入到以下界面,connection上面 ,右键>add new entry 2: 搜索自己需要的系统名称. 3:一直next,直到完成 4: 双击该系统,进入以 ...

  8. 【LeetCode每天一题】Longest Valid Parentheses(最长有效括弧)

    Given a string containing just the characters '(' and ')', find the length of the longest valid (wel ...

  9. 虚拟IP技术

    虚拟IP技术在高可用领域像数据库SQLSERVER.web服务器等场景下使用很多,很疑惑它是怎么实现的,偶然,发现了一种方式可以实现虚拟ip.它的原理在于同一个物理网卡,是可以拥有多个ip地址的,至于 ...

  10. 梯度下降法(BGD、SGD)、牛顿法、拟牛顿法(DFP、BFGS)、共轭梯度法

    一.梯度下降法 梯度:如果函数是一维的变量,则梯度就是导数的方向:      如果是大于一维的,梯度就是在这个点的法向量,并指向数值更高的等值线,这就是为什么求最小值的时候要用负梯度 梯度下降法(Gr ...