我是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类[name
]的无效属性Country
:Bean属性name
是不可写的或具有无效的setter方法。您是说cname
吗?
我还通过许多其他示例注意到了这种情况。
有人可以帮我吗?
答案 0 :(得分:2)
这是因为您的bean定义表明Customer
是 Country
的父级,但是您的课程Country
不是 < strong>扩展 Customer
<bean id ="country" class="Country" parent="customer">
所以您有两个选择
parent="customer"
public class Country extends Customer{...
答案 1 :(得分:-1)
在您的bean中,class属性应具有与该类对应的包名称。喜欢
<bean id = "customer" class = "com.test.entity.Customer">
<property name = "name" value = "Garima"/>
</bean>
<bean id ="country" class="com.test.entity.Country" parent="customer">
<property name = "cname" value = "India"/>
<property name = "city" value = "Delhi"/>
</bean>