gpt4 book ai didi

java - 指定了 1 个构造函数参数,但在 bean 中找不到匹配的构造函数,为什么 Autowiring 名称不适用于构造函数参数

转载 作者:行者123 更新时间:2023-12-01 20:02:04 24 4
gpt4 key购买 nike

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

Please avoid answering by <constructor-arg ref="address">

下面是我的场景

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

地址.java

public class Address {
private String place;

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

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

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)

提前致谢!!.

最佳答案

如果您使用 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" 可以。

关于java - 指定了 1 个构造函数参数,但在 bean 中找不到匹配的构造函数,为什么 Autowiring 名称不适用于构造函数参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47931596/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com