如果解析bean时存在歧义,Spring会抛出异常 [英] Will Spring throw an exception if there is ambiguity when resolving a bean

查看:89
本文介绍了如果解析bean时存在歧义,Spring会抛出异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当有多个相同类型的bean时,我可以让Spring引发异常吗?当前的行为似乎是注入 null .

Can I get Spring to throw an exception when there is more than one bean with the same type? The current behavior seems to be to inject null.

推荐答案

您应该会得到一个错误,是的.

You should get an error, yes.

来自 http://docs.spring.io/spring/docs/4.2.x/spring-framework-reference/html/beans.html#beans-factory-autowire :

容器中的多个bean定义可能与要自动装配的setter方法或构造函数参数指定的类型匹配.对于数组,集合或地图,这不一定是问题.但是,对于期望单个值的依赖项,不会任意解决此歧义.如果没有唯一的bean定义可用,则会引发异常.

Multiple bean definitions within the container may match the type specified by the setter method or constructor argument to be autowired. For arrays, collections, or Maps, this is not necessarily a problem. However for dependencies that expect a single value, this ambiguity is not arbitrarily resolved. If no unique bean definition is available, an exception is thrown.

您应该得到一个运行时异常,错误如下:

You should get a runtime exception with an error like:

由以下原因引起:org.springframework.beans.factory.NoUniqueBeanDefinitionException:没有定义类型为[...]的合格bean:期望的单个匹配bean,但找到了2:...

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

这篇关于如果解析bean时存在歧义,Spring会抛出异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆