简体   繁体   English

无法在Spring中使用构造函数自动装配bean

[英]Not able to autowire a bean using constructor in Spring

Im new to spring. 我是春天新手。 I'm trying to autowire a bean using constructor using spring. 我正在尝试使用spring使用构造函数自动装配bean。 Here is the code 这是代码

<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>

location class 位置等级

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);
}

}

Address class 地址类

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 + "]";
}

Tester 测试仪

 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();

}

}

I'm setting one of the field value through constructor arg. 我通过构造函数arg设置了一个字段值。 and class should be injected. 和类应该注入。 WHat could be the problem here? 这可能是什么问题?

The error log says 错误日志说

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?

It seems like Location has two arguments so: 似乎Location有两个参数:

<bean id="location" class="com.ibm.spring.Location">
    <constructor-arg name="pincode" value="110976"></constructor-arg>
     <constructor-arg ref="address"></constructor-arg>
</bean>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM