指定了1个构造函数参数但在bean中找不到匹配的构造函数,为什么auto-wire byname不能与constructor-arg

时间:2017-12-21 19:30:05

标签: java spring

如何设置emp Id及其地址,我还想保留autowire =“byName”作为地址。

  

请避免通过<constructor-arg ref="address">

回答

以下是我的方案

弹簧-config.xml中

 <?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
    xsi:schemaLocation="http://www.springframework.org/schema/beans   
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">


    <bean id="empBean" class="com.spring.SpringCoreIOC.autowiring.Employee"
        autowire="byName">
        <constructor-arg index="0" type="int" value="11111" />
    </bean>

    <bean id="address" class="com.spring.SpringCoreIOC.autowiring.Address">
        <constructor-arg value="Secret Chowk" />
    </bean>
</beans>  

Address.java

public class Address {
    private String place;

    public Address(String place) {
        super();
        this.place = place;
    }
    public String toString() {
        return place;
    }

Employee.java,类有自己的id,int类型和地址地址类型

public class Employee {

    private Address address;
    private int id;

    public Employee(int id, Address address) {
        super();
        this.id = id;
        this.address = address;
    } }

我遇到的错误如下

Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'empBean' defined in class path resource [autowiring_byNameByTag.xml]: 1 constructor arguments specified but no matching constructor found in bean 'empBean' (hint: specify index and/or type arguments for simple parameters to avoid type ambiguities)

提前致谢!!。

2 个答案:

答案 0 :(得分:2)

如果你使用autowire="byName"并希望将id参数传递给构造函数,那么你应该使用只有id参数的构造函数:public Employee(int id)并通过setter设置你的地址:

public class Employee {

    private Address address;
    private int id;

    public Employee(int id) {
        super();
        this.id = id;
    } 

    public Address getAddress() {
        return address;
    }
    public void setAddress(Address address) {
        this.address = address;
    }
}

因为autowire="byName"不适用于构造函数参数,但autowire="constructor"不起作用。

答案 1 :(得分:1)

更多: 我希望通过Ivan,Kirill提到的链接来反映我理解的理解。

  

<autowire="byName">在这种情况下,它正在观看学生班   属性,如id =“address”as address是Student的属性;

<bean id="studentBean" class="com.lokesh.SpringCore.entity.Student" autowire="byName"/>
<bean id="address" class="com.lokesh.SpringCore.entity.Address">
        <constructor-arg value="EARTH" />
</bean>

  

<autowire="constructor">正在考虑构造函数arg,   属性无关紧要

<bean id="studentBean" class="com.lokesh.SpringCore.entity.Student" autowire="constructor">
    <constructor-arg type="int" value="12444" />
</bean>

 <bean id="anything" class="com.lokesh.SpringCore.entity.Address">
        <constructor-arg value="EARTH" />
    </bean>

如果我没有涉及任何方面,请纠正我或加上你的观点。

谢谢!