我是春天新手。我正在尝试使用spring使用构造函数自动装配bean。这是代码
<bean id="location" class="com.ibm.spring.Location">
<constructor-arg name="pincode" value="110976"></constructor-arg>
</bean>
<bean id="address" class="com.ibm.spring.Address">
<property name="id" value="2"></property>
<property name="street" value="shahjahan"></property>
</bean>
public class Location {
private Address address;
private String pincode;
public void setAddress(Address address) {
this.address = address;
}
@Autowired
public Location(Address address, String pincode) {
super();
this.address = address;
this.pincode = pincode;
}
public void getTotalAddress() {
System.out.println(this.pincode + "::"+this.address);
}
}
public class Address {
private int id;
private String street;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getStreet() {
return street;
}
public void setStreet(String street) {
this.street = "Kkp";
}
@Override
public String toString() {
return "Address [id=" + id + ", street=" + street + "]";
}
public class SpringTester {
public static void main(String[] args) {
String configLoc = "com/ibm/spring/config/applicationContext.xml";
ApplicationContext ctx = new ClassPathXmlApplicationContext(configLoc);
Location l = (Location) ctx.getBean("location");
l.getTotalAddress();
}
}
我通过构造函数arg设置了一个字段值。和类应该注入。这可能是什么问题?
错误日志显示
Error creating bean with name 'location' defined in class path resource [com/ibm/spring/config/applicationContext.xml]: Unsatisfied dependency expressed through constructor parameter 0: Ambiguous argument values for parameter of type [com.ibm.spring.Address] - did you specify the correct bean references as arguments?
答案 0 :(得分:0)
似乎Location有两个参数:
<bean id="location" class="com.ibm.spring.Location">
<constructor-arg name="pincode" value="110976"></constructor-arg>
<constructor-arg ref="address"></constructor-arg>
</bean>