1:分析
我们在定义bean的时候,可能存在多个bean存在相同属性的情况,并且这些相同的属性我们要给的值也是相同的,正常情况下,需要重复配置多次,spring通过提供abstract=true
帮我们解决了这个问题,所以abstract=true其实就是封装属性的一个配置,并不是配置bean的,而配置完毕后,我们真实的bean如果是想要直接使用而不是重复配置一次的话,则可以通过parent=”公共配置的bean名称“
的方式来使用。
2:实例
2.1:定义类1
有属性,name
,age
,hobby
:
public class MyCls1 {
private String name;
private String age;
private String hobby;
...getter setter tostring...
}
2.2:定义类2
有属性,name
,age
,gender
,和2.1:定义类1
中定义的类name和age是重复的属性:
public class MyCls2 {
private String name;
private String age;
private String gender;
...getter setter tostring...
}
2.3:定义公共配置
<bean id="basePropConfig" abstract="true">
<property name="name" value="张三"/>
<property name="age" value="20"/>
</bean>
2.4:定义2个bean
<bean id="cls1" class="yudaosourcecode.abstractandparent.MyCls1" parent="basePropConfig">
<property name="hobby" value="篮球"/>
</bean>
<bean id="cls2" class="yudaosourcecode.abstractandparent.MyCls2" parent="basePropConfig">
<property name="gender" value="男"/>
</bean>
2.5:完整配置
<?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.xsd">
<bean id="basePropConfig" abstract="true">
<property name="name" value="张三"/>
<property name="age" value="20"/>
</bean>
<bean id="cls1" class="yudaosourcecode.abstractandparent.MyCls1" parent="basePropConfig">
<property name="hobby" value="篮球"/>
</bean>
<bean id="cls2" class="yudaosourcecode.abstractandparent.MyCls2" parent="basePropConfig">
<property name="gender" value="男"/>
</bean>
</beans>
2.6:测试代码
@Test
public void testAbstractAndParent() {
ClassPathXmlApplicationContext ac = new ClassPathXmlApplicationContext("classpath:abstractandparent.xml");
System.out.println(ac.getBean("cls1", MyCls1.class));
System.out.println(ac.getBean("cls2", MyCls2.class));
}
运行:
{"age":"20","hobby":"篮球","name":"张三"}
{"age":"20","gender":"男","name":"张三"}
可以看到已经继承了公共的属性。