spring错误:bean实例类中的属性类型与spring配置文件中的构造器属性类型不对应

错误原因:bean实例类中的属性类型与spring配置文件中的构造器属性类型不对应所导致,这种情况多出在使用类型指定构造器参数;
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'userId' defined in class path resource [com/java/f_xml/a_constructor/beans.xml]: Unsatisfied dependency expressed through constructor argument with index 0 of type [int]: Ambiguous constructor argument types - did you specify the correct bean references as constructor arguments?
Related cause: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'userId' defined in class path resource [com/java/f_xml/a_constructor/beans.xml]: Unsatisfied dependency expressed through constructor argument with index 1 of type [int]: Ambiguous constructor argument types - did you specify the correct bean references as constructor arguments?
 这种错误是因为构造器中的type属性 不会自动对应拆箱装箱属性类型 ,简单点说就是类中使用的是基本数据类型,配置文件中对应的type属性值就要是基本数据类型;类中使用的是类类型,配置文件中对应的type属性值就要是包名加上类类型;
public class User {
private String username;
private int id;//可以为private Integer id;对应的配置文件type="java.lang.Integer",返回数据库字段值是null的话,int类型会报错。int是基本数据类型,其声明的是变量,而null则是对象。所以建议用integer;
private int age;
public User(int id, int age) {
super();
this.id = id;
this.age = age;
}
public User(String username, int id) {
super();
this.username = username;
this.id = id;
}
}
xml:<bean id="userId" class="com.java.f_xml.a_constructor.User" >
<constructor-arg index="0" type= "java.lang.String" value="jack"></constructor-arg>
<constructor-arg index="1" type= "int" value="123"></constructor-arg>
</bean>

参考文档:

猜你喜欢

转载自blog.csdn.net/zpr5554321/article/details/79313450