gpt4 book ai didi

java - bean 类 [Country] : Bean property 'name' is not writable or has an invalid setter method. 的属性 'name' 无效 您的意思是 'cname' 吗?

转载 作者:行者123 更新时间:2023-12-02 01:14:52 27 4
gpt4 key购买 nike

我是spring的新手,所以我只是想在spring中实现继承。

Customer.java

public class Customer {

String name;

public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}

Country.java

public class Country {

String cname;
String city;
public String getCname() {
return cname;
}
public void setCname(String cname) {
this.cname = cname;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
}

Main.java

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

public class Main {

public static void main(String args[]){

ApplicationContext context = new ClassPathXmlApplicationContext("Bean1.xml");
Customer cus = (Customer) context.getBean("customer");
System.out.println(cus.getName());
Country con = (Country) context.getBean("country");
System.out.println(con.getCname());

}
}

Bean1.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 = "customer" class = "Customer">
<property name = "name" value = "Garima"/>
</bean>

<bean id ="country" class="Country" parent="customer">
<property name = "cname" value = "India"/>
<property name = "city" value = "Delhi"/>
</bean>
</beans>

每次我在 Bean1.xml 中运行没有父项的情况时,它都运行良好。一旦我添加了parent,我就会收到下面提到的错误。错误:bean 类 [Country] 的属性 name 无效:Bean 属性 name 不可写或具有无效的 setter 方法。您指的是 cname 吗?我也注意到了这个案例以及许多其他例子。有人可以帮我解决这个问题吗?

最佳答案

这是因为您的 bean 定义表明 Customer Country 的父级,但您的类 Country 延长 客户

<bean id ="country" class="Country" parent="customer">

所以你有两个选择

  1. 要么从您的 bean 定义中删除 parent="customer"
  2. 在国家/地区类别中扩展客户,例如public class Country 扩展 Customer{...

关于java - bean 类 [Country] : Bean property 'name' is not writable or has an invalid setter method. 的属性 'name' 无效 您的意思是 'cname' 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58831219/

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