【问题标题】:Spring Test / JUnit problem - unable to load application contextSpring Test / JUnit 问题 - 无法加载应用程序上下文
【发布时间】: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


    【解决方案1】:

    试试&lt;ref/&gt; 而不是&lt;idref/&gt;。

    “idref 元素只是将容器中另一个 bean 的 id 传递给 &lt;constructor-arg/&gt; 或 &lt;property/&gt; 元素的一种防错方法。”

    【讨论】:

    • 解决了“无法创建应用程序上下文”错误,但在测试中给我带来了 NullPointerException。看起来 Spring 没有注入依赖项。
    • 我需要在测试类的字段上添加“@Resource”注解。使用“ref”而不是“idref”解决了这个问题。作为一个新的 Spring 开发人员,我不得不说关于这一点的文档真的很糟糕。听起来 idref 更像是一种引用 bean 的“类型安全”方式,而实际上它是一种引用 bean 的字符串名称的方式。非常混乱....
    猜你喜欢
    • 2012-05-24
    • 2019-06-16
    • 2021-05-09
    • 2013-02-03
    • 2018-07-11
    • 1970-01-01
    • 2015-04-27
    • 2011-05-12
    • 1970-01-01
    相关资源
    最近更新 更多