问题描述
我已经在spring配置文件中使用spring util名称空间声明了以下列表:
I have declared following list using spring util namespace in my spring configuration file:
<util:list id="childList">
<ref bean="child1"/>
<ref bean="child2"/>
<ref bean="child3"/>
</util:list>
,其中所有引用bean均标有@Componant批注,并且正在创建它们各自的bean.但是,每当我尝试自动连线任何bean属性时,例如:
where all reference bean are marked with @Componant annotation and their respective beans are creating. But whenever I am trying to Autowired any beans property like:
@Component
public class ListTest{
@Autowired
@Qualifier("childList")
private List<IParent> list;
public List<IParent> getList() {
return list;
}
}
给出如下异常:org.springframework.beans.factory.BeanCreationException:创建名称为'listTest'的bean时出错:自动连接依赖项的注入失败;嵌套的异常是org.springframework.beans.factory.BeanCreationException:无法自动装配字段:私有java.util.List com.spring3.componentScanFilterTest.ListTest.list;嵌套的异常是org.springframework.beans.factory.NoSuchBeanDefinitionException:没有找到类型为[com.spring3.componentScanFilterTest.IParent]的匹配bean依赖项[com.spring3.componentScanFilterTest.IParent的集合]:至少需要1个符合以下条件的bean:自动关联此依赖项的候选对象.依赖注释:{@ org.springframework.beans.factory.annotation.Autowired(required = true),@ org.springframework.beans.factory.annotation.Qualifier(value = childList)}
Gives exception as: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'listTest': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private java.util.List com.spring3.componentScanFilterTest.ListTest.list; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [com.spring3.componentScanFilterTest.IParent] found for dependency [collection of com.spring3.componentScanFilterTest.IParent]: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true), @org.springframework.beans.factory.annotation.Qualifier(value=childList)}
但是如果我用作@,则不是@Autowired和@Qualifier: @Resource(name ="childList")
But instead of @Autowired and @Qualifier if I use as: @Resource(name="childList")
有效.为什么?据我了解,@ Autowired用于按类型自动匹配匹配的属性,而@Qualifier用于从多个模棱两可的bean中选择任何一个bean.
It works. Why? As per my understanding @Autowired is used to autowire the property matching by type and @Qualifier is used to select any one bean from multiple ambiguous beans.
请解释.
推荐答案
Spring 文档说.
由于这种语义差异的特定结果,本身定义为集合或映射类型的bean无法通过@Autowired注入,因为类型匹配不适用于它们.对此类bean使用@Resource,通过唯一的名称引用特定的collection或map bean.
希望这可以清除您的疑问.
Hope this clear your doubt.
这篇关于Bean的属性不是通过util:list对象设置的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!