我有一个bean,我想使用Spring util命名空间注入一个命名列表, <util:list id="myList">但Spring正在寻找一个类型为String的bean集合.我破碎的测试是:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
public class ListInjectionTest {
@Autowired @Qualifier("myList") private List<String> stringList;
@Test public void testNotNull() {
TestCase.assertNotNull("stringList not null", stringList);
}
}
Run Code Online (Sandbox Code Playgroud)
我的背景是:
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:util="http://www.springframework.org/schema/util"
xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-2.5.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd">
<util:list id="myList">
<value>foo</value>
<value>bar</value>
</util:list>
</beans>
Run Code Online (Sandbox Code Playgroud)
但我明白了
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [java.lang.String] found for dependency [collection of java.lang.String]: 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=myList)}
at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:726)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:571)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:412)
Run Code Online (Sandbox Code Playgroud)
这让我很困惑,因为我认为这将是预期的工作方式.
ska*_*man 169
这是由于3.11.2中指定的@Autowired行为的一个相当模糊的部分.@Autowired:
也可以
ApplicationContext通过将注释添加到期望该类型的数组的字段或方法来提供特定类型的所有bean ...这同样适用于打字集合......
换句话说,通过说@Autowired @Qualifier("myList") List<String>,你实际上要求"给我所有java.lang.String具有限定符"myList" 类型的bean的列表.
该解决方案在3.11.3中提到.使用限定符微调基于注释的自动装配:
如果您打算按名称表达注释驱动的注入,请不要主要使用
@Autowired- 即使技术上能够通过@Qualifier值引用bean名称.相反,更喜欢JSR-250@Resource注释,该注释在语义上定义为通过其唯一名称标识特定目标组件,声明的类型与匹配过程无关.作为这种语义差异的特定结果,
@Autowired由于类型匹配不适用于它们,因此无法将自身定义为集合或映射类型的bean注入 .使用@Resource这样的豆子,通过唯一的名称指的是特定集合/图豆.
所以在你的测试中使用它,它工作正常:
@Resource(name="myList") private List<String> stringList;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
36685 次 |
| 最近记录: |