作用
比如有一个animal类,有字段name、legs,想通过animal类创建多个4条腿的动物实例,每个动物的名字不一样,此时我们可以parent字段,通过一个Animal类创建多个实例。
实现
//Animal类
public class Animal {
private int legs;
private String name;
@Override
public String toString() {
return "Animal{" +
"legs=" + legs +
", name='" + name + '\'' +
'}';
}
public int getLegs() {
return legs;
}
public void setLegs(int legs) {
this.legs = legs;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
<?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:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">
<bean id="animal" class="com.chen.Animal" abstract="true">
<property name="legs" value="4"/>
</bean>
<bean id="animal1" parent="animal">
<property name="name" value="monkey"/>
</bean>
<bean id="animal2" parent="animal">
<property name="name" value="cat"/>
</bean>
</beans>
//运行类
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
Animal animal1 = context.getBean("animal1", Animal.class);
System.out.println(animal1);
Animal animal2 = context.getBean("animal2", Animal.class);
System.out.println(animal2);
}
输出
说明
当我们需要创建的对象有很多通用的属性,比如上例中的leg都等于4,那么我只需要在parent的bean定义一个leg等于4,在每个实例的bean中只需要定义name即可,得到的对象自然就包含leg等于4