我们壹起来看看以下三个类,看它们如何使用 Spring 来映射。
public abstract class SuperBean {
private int id;
private String name;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
public class SubBean extends SuperBean {
private String newProperty;
public String getNewProperty() {
return newProperty;
}
public void setNewProperty(String newProperty) {
this.newProperty = newProperty;
}
}
public class DifferentBean {
private int id;
private String name;
private String myProperty;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getMyProperty() {
return myProperty;
}
public void setMyProperty(String myProperty) {
this.myProperty = myProperty;
}
}
我们开始在 Spring 中来映射它们:
<?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-2.0.xsd">
<bean id="superBean" abstract="true"
class="com.stevideter.spring.SuperBean">
<property name="id" value="1" />
<property name="name" value="superBean" />
</bean>
<bean id="subBean" class="com.stevideter.spring.SubBean"
parent="superBean">
<property name="id" value="2" />
<property name="newProperty" value="subBean" />
</bean>
<bean id="differentBean" class="com.stevideter.spring.DifferentBean"
parent="superBean">
<property name="id" value="3" />
<property name="myProperty" value="differentBean" />
</bean>
</beans>
并且现在我们写壹个简单的应用来展示使用这些映射到底会发生什么情况:
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class TestClass {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext(new String[] {"applicationContext.xml"});
SubBean subBean = (SubBean)context.getBean("subBean");
System.out.printf("ID: %d, Name: %s, Property: %s\n",
subBean.getId(), subBean.getName(), subBean.getNewProperty());
DifferentBean differentBean = (DifferentBean)context.getBean("differentBean");
System.out.printf("ID: %d, Name: %s, Property: %s\n",
differentBean.getId(), differentBean.getName(), differentBean.getMyProperty());
}
}
如果我们运行这个类,会获取如下结果:
ID: 2, Name: superBean, Property: subBean
ID: 3, Name: superBean, Property: differentBean
我们从这个例子中了解到,如果你的 bean 类没有继承别的类,可以使用 parent 属性来映射 parent bean 的定义。壹个必要条件是子类必须与父类保持兼容,也就是说,子类必须具有父类中已经定义过的所有属性。事实上, Spring 官方文档 说你完全不需要声明壹个继承自父类的新对象。
我发现将父类定义作为壹个模板的方法很有用,我们可以将其作为壹个面向对象风格的继承,另外壹种想法就是将其作为子类的父接口,你必须继承这些发生以便使用其定义。
英文原文:http://www.stevideter.com/2008/03/22/using-parent-bean-definitions-in-spring/