本文介绍了自动装配Spring超类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
为什么Spring在自动装配过程中会自动选择超类类型?
Why does Spring automatically choose the superclass types during autowiring?
例如,如果我有
@Component
public class Foo {}
@Component
public class Bar extends Foo {}
有人自动接线
@Autowired
private Foo foo;
Spring为什么总是选择父类型Foo
?这不应该是"模糊"映射(并导致Spring引发错误)吗?
How come Spring always chooses the supertype Foo
? Shouldn't this be an "ambiguous" mapping (and cause Spring to throw an error)?
从技术上讲,您不是有两个 Foo
个候选人吗? (例如,当从Foo中删除@Component时,Bar被自动选择)
Don't you technically have two Foo
candidates? (e.g., Bar gets automatically picked when @Component is removed from Foo...)
推荐答案
这可能是因为自动装配是通过名称而不是类型完成的.如果我使用xml这样设置Bean:
That might be because the autowiring is done by name, not type. If I setup my bean using xml like this:
<bean id="foo1" class="Foo"/>
<bean id="foo2" class="Bar"/>
并尝试按类型自动接线:
And attempt to autowire by type:
@Autowired private Foo aFoo;
我知道
org.springframework.beans.factory.NoSuchBeanDefinitionException: No unique bean of type [Foo]
这篇关于自动装配Spring超类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!