<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"> <bean id="baseStudent" class="Student"> <property name="name"><value>zhangsan</value></property> <property name="nums"> <list> <value>1</value> <value>2</value> <value>3</value> </list> </property> </bean> <bean id="Student" parent="baseStudent"> <property name="nums"> <list> <value>1</value> <value>2</value> </list> </property> </bean> </beans>
public class Student { private String name; private List<Integer> nums; public String getName() { return name; } public void setName(String name) { this.name = name; } public List<Integer> getNums() { return nums; } public void setNums(List<Integer> nums) { this.nums = nums; } }
test代码
public class ApplicationContextTest { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml"); System.out.println("------------BaseStudent---------"); Student student = applicationContext.getBean("baseStudent",Student.class); System.out.println(student.getName()); for (Integer num : student.getNums()) { System.out.println(num); } System.out.println("------------Student---------"); Student student2 = applicationContext.getBean("Student",Student.class); System.out.println(student2.getName()); for (Integer num : student2.getNums()) { System.out.println(num); } } }
输出结果:
------------BaseStudent---------
zhangsan
1
2
3
------------Student---------
zhangsan
1
2
结果分析:覆盖了baseStudent配置的bean的nums属性
修改配置文件,设置merge属性
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"> <bean id="baseStudent" class="Student"> <property name="name"><value>zhangsan</value></property> <property name="nums"> <list> <value>1</value> <value>2</value> <value>3</value> </list> </property> </bean> <bean id="Student" parent="baseStudent"> <property name="nums" > <list merge="true"> <!-- 设置merge为true --> <value>1</value> <value>2</value> </list> </property> </bean> </beans>
输出结果:
------------BaseStudent---------
zhangsan
1
2
3
------------Student---------
zhangsan
1
2
3
1
2
结果分析:将Student的bean的List集合nums 与 baseStudent的List集合nums合并。
结论:当bean的配置文件中,某个bean配置继承了另外一个bean的配置。
1 对于非集合属性,如果重写了父bean配置的属性(即属性名和父bean配置的属性名一样),则就重写了父配置属性。
2 对于集合属性,如果重写了配置属性,不设置merge属性,则也是重写了该集合。当merge=true,则将这个集合与父bean配置的集合合并。
即List将合并在一块。Set集合由于不能重复,如果重复则会覆盖父配置的值。Map集合键不能重复,重复也会覆盖。
总结:bean配置文件中bean的继承(即parent属性)与Java实体类的继承没有关系。 也可以理解成是bean配置的多态性吧。