gpt4 book ai didi

java - 无法解析匹配的构造函数。Spring 依赖注入(inject)的歧义问题

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:22:56 24 4
gpt4 key购买 nike

我在执行 spring 程序时遇到错误“无法解析匹配的构造函数(提示:为简单参数指定索引/类型/名称参数以避免类型歧义)”。我是 Spring 核心的新手,正在尝试学习该框架。下面是代码:

学生.java

package com.inject.test;

public class Student {

private String name;
private String className;
private Address address;



public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getClassName() {
return className;
}
public void setClassName(String className) {
this.className = className;
}


}

地址.java

package com.inject.test;

public class Address {

private String city;
private String state;




public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}

}

测试.java

package com.inject.test;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Test {

public static void main(String[] args) {

@SuppressWarnings("resource")
ApplicationContext context = new ClassPathXmlApplicationContext("file:com/applicationContext.xml");
Student student = (Student) context.getBean("student");

System.out.println("Name: " + student.getName());
System.out.println("Class: " + student.getClassName());

Address studentAddress = student.getAddress();


System.out.println("Student Address: ");
System.out.println("City: " + studentAddress.getCity());
System.out.println("State: " + studentAddress.getState());
}

}

applicationContext.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

<bean id="student" class="com.inject.test.Student">
<property name="name" value="Jai"/>
<property name="className" value="MCA"/>
<constructor-arg ref="address" type="java.lang.String"/>
</bean>

<bean id="address" class="com.inject.test.Address">
<property name="city" value="Hyderabad"/>
<property name="state" value="Telangana"/>
</bean>

</beans>

解决构造函数问题应该做哪些修改,请指教。

最佳答案

您的 xml 配置指定了一个包含地址的构造函数参数,但您的 Student 类没有接受任何参数的构造函数。

要么添加适当的构造函数,要么将构造函数参数更改为 xml 配置中的属性。

关于java - 无法解析匹配的构造函数。Spring 依赖注入(inject)的歧义问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37648984/

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