简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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