【发布时间】:2017-03-02 18:04:54
【问题描述】:
在 Spring 3.1.3.RELEASE 项目中,我想创建并自动装配一个列表,其中包含一些服务的一些枚举。
不幸的是,自动装配失败 (NoSuchBeanDefinitionException),而我可以在上下文中检索 bean 并手动装配依赖项。
这是一个展示问题的小测试用例(使用 Spring 3.1.3 和 JUnit):
XML 上下文(int package /junk):
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:util="http://www.springframework.org/schema/util"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<context:component-scan base-package="junk"/>
<util:list id="myList" value-type="junk.GreatThings">
<value>SUPER</value>
<value>COOL</value>
</util:list>
</beans>
枚举:
package junk;
public enum GreatThings {AMAZING, GREAT, SUPER, COOL}
测试类(在垃圾包中 - 为了清楚起见,我删除了导入):
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath*:junkcontext.xml"})
public class TestAutowiringSupport {
@Autowired @Qualifier("myList") List<GreatThings> greatThings;
@Test public void testSuperCool() {
Assert.assertThat(greatThings, hasItem(SUPER));
Assert.assertThat(greatThings, hasItem(COOL));
}
}
这会导致 NoSuchBeanDefinitionException。 我试图用我的 bean id 放置一个 @Qualifier 来帮助 Spring 执行连接但没有任何成功。
如果我使用 Spring 生命周期回调来取回 bean 并手动连接它,那就没问题了。
编译和运行良好的版本:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath*:junkcontext.xml"})
public class TestAutowiringSupport implements ApplicationContextAware
{
ApplicationContext ctx;
List<GreatThings> greatThings;
@Override
public void setApplicationContext(ApplicationContext ctx) throws BeansException {this.ctx = ctx;}
@PostConstruct
public void manualWiring() {greatThings = (List<GreatThings>) ctx.getBean("myList");}
@Test public void testSuperCool() {
Assert.assertThat(greatThings, hasItem(SUPER));
Assert.assertThat(greatThings, hasItem(COOL));
}
}
在这种情况下自动装配有什么问题?
【问题讨论】:
-
尝试在
TestAutowiringSupport中添加@Qualifier("myList")到greatThings -
我试过了,但它做同样的事情...... NoSuchBeanDefinitionException
-
尝试将@Component 添加到
TestAutowiringSupport类