【发布时间】:2010-05-19 13:41:07
【问题描述】:
我是第一次使用 Spring,一定是做错了什么。我有一个包含多个 Bean 实现的项目,现在我正在尝试使用 Spring Test 和 JUnit 创建一个测试类。我正在尝试使用 Spring Test 将自定义 bean 注入测试类。
这是我的 test-applicationContext.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns=".............">
<bean
id="MyUuidFactory"
class="com.myapp.UuidFactory"
scope="singleton" >
<property name="typeIdentifier" value="CLS" />
</bean>
<bean id="ThingyImplTest"
class="com.myapp.ThingyImplTest"
scope="singleton">
<property name="uuidFactory">
<idref local="MyUuidFactory" />
</property>
</bean>
</beans>
MyUuidFactory 实例的注入伴随着测试类中的以下代码:
private UuidFactory uuidFactory;
public void setUuidFactory(UuidFactory uuidFactory) {
this.uuidFactory = uuidFactory;
}
但是,当我去运行测试(在 Eclipse 或命令行中)时,我收到以下错误(为简洁起见省略了堆栈跟踪):
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'MyImplTest' defined in class path resource [test-applicationContext.xml]:
Initialization of bean failed; nested exception is org.springframework.beans.ConversionNotSupportedException:
Failed to convert property value of type 'java.lang.String' to required type 'com.myapp.UuidFactory' for property 'uuidFactory';
nested exception is java.lang.IllegalStateException:
Cannot convert value of type [java.lang.String] to required type [com.myapp.UuidFactory] for property 'uuidFactory':
no matching editors or conversion strategy found
有趣的是,Eclipse/Spring XML 编辑器显示我拼错任何类型或 idref 的错误。如果我将 bean 留在其中,但注释掉依赖注入,则一切正常,直到我在运行测试时收到 NullPointerException ......这是有道理的。
【问题讨论】:
标签: xml spring dependency-injection junit testing