java - Spring <constructor-arg> 元素必须指定一个 ref 或 value

标签 java spring constructor-injection

我在使用 Spring 和构造函数注入(inject)时遇到问题。我想动态创建具有名称 (String) 和特殊 id (long) 的对象。

但是当spring.xml文件加载的时候出现异常。

Exception in thread "main" java.lang.ExceptionInInitializerError

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

我的 spring.xml:

    <bean id="someBean" class="someClass" >
        <constructor-arg index="0" type="java.lang.String" value=""/>       
        <constructor-arg index="1" type="long" value=""/>
    </bean>
</beans>

那有什么问题呢?构造函数参数的索引为 1(而不是 0,正如异常所说)

最佳答案

在构造函数参数中,您可以使用原始类型 long 和值 0,或包装器类型 java.lang.Long 和一个空值。此外,为了控制一切,我会将第二个参数的值显式设置为 0。

关于java - Spring <constructor-arg> 元素必须指定一个 ref 或 value,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17260258/

相关文章:

java - Spring重载构造函数注入(inject)

java - 从 Android Java 调用 native 函数 - JNI 的替代方案

java - 我应该如何将 JpaRepository.findOne() 与 SpringBoot 一起使用?

java - JAVA 中的 super() 函数

Java Swing 为游戏添加组件

java - Spring 执行器自定义指标(平均、最小、最大响应时间)

spring - 从 Controller 重定向到项目外的不同 URL

.net - 依赖注入(inject) - 构造

java - 使用 JDBC 和 Spring 访问关系数据时出现嵌套 Servlet 异常

java - 使用抽象 Spring bean 作为构造函数参数