14

我有以下spring bean配置

  <bean id="fileBean" class="java.io.File">
    <constructor-arg type="java.lang.String" 
                     value="$prop{file.path.property}" />    
  </bean>

我收到以下错误

org.springframework.beans.factory.UnsatisfiedDependencyException: 
Error creating bean with name 'fileBean' defined in class path resource [context.xml]:  
Unsatisfied dependency expressed through constructor argument with index 0 of type
[java.net.URI]: Ambiguous constructor argument types - did you specify the correct 
bean references as constructor arguments?

java.io.File 只有一个带有单个 String 参数的构造函数,所以我不确定为什么这是模棱两可的。任何帮助表示赞赏。

4

2 回答 2

26

找到解释正在发生的事情的链接。事实证明,如果没有指定参数索引,spring 将按类型匹配参数。在这种情况下,spring 接受我的单个 String 参数并将其传递给 java.io.File 构造函数,该构造函数接受两个字符串。这可以通过指定构造函数参数索引来解决。

<bean id="fileBean" class="java.io.File">
  <constructor-arg index="0"
                   type="java.lang.String" 
                   value="$prop{file.path.property}" />    
</bean>
于 2011-09-06T23:21:59.987 回答
5

只是我的两分钱:我今天遇到了完全相同的问题。我有一个单元测试来检查 Spring 是否可以读取我的 XML 配置并生成所有必要的 bean。它失败了,因为我编辑了错误的 XML 文件。我正在编辑来自 Ant 构建的“dist”版本,而不是来自源代码控制的正确版本。

经验教训:仔细阅读那些 Spring 异常消息(带有 XML 文件路径) !

于 2014-05-19T10:04:20.903 回答