Spring中继承Bean的配置
1、子 Bean 从父 Bean 中继承配置, 包括 Bean 的属性配置
applicationContext-relative.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.xsd">
<bean id="dept" class="com.zm.bean.relative.Dept">
<property name="deptId" value="1"/>
<property name="deptName" value="秘书部"/>
</bean>
<!--使用继承Bean。使用parent属性指定要继承的Bean-->
<bean id="dept02" parent="dept"></bean>
</beans>
测试类中:
@Test
public void test01(){
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext-relative.xml");
Dept dept = context.getBean("dept", Dept.class);
System.out.println(dept);
//使用继承Bean。dept02这个对象继承了dept这个对象的信息(配置信息)
Dept dept02 = context.getBean("dept02", Dept.class);
System.out.println(dept02);
}
运行结果:
2、子 Bean 也可以覆盖从父 Bean 中继承过来的配置
xxx.xml配置文件中:
<bean id="dept" class="com.zm.bean.relative.Dept">
<property name="deptId" value="1"/>
<property name="deptName" value="秘书部"/>
</bean>
<!--子 Bean 可以覆盖从父 Bean 继承过来的配置-->
<bean id="dept03" parent="dept">
<property name="deptName" value="开发部"/>
</bean>
测试类中:
@Test
public void test01(){
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext-relative.xml");
Dept dept = context.getBean("dept", Dept.class);
System.out.println(dept);
//使用继承Bean。子Bean可以覆盖从父Bean继承过来的配置
Dept dept03 = context.getBean("dept03", Dept.class);
System.out.println(dept03);
}
运行结果:
3、父 Bean 可以作为配置模板, 也可以作为 Bean 实例。若只想把父 Bean 作为模板, 可以设置 的abstract属性为 true, 这样 Spring 将不会实例化这个 Bean
抽象Bean:Bean的abstract属性的值为true。这样的Bean不能被IOC容器实例化,只能被用来继承配置。若一个Bean的class属性没有指定,则该Bean必须是一个抽象Bean。
<!--抽象bean:bean的abstract属性的值为true。B这样的Bean不能被IOC容器实
例化,只能被用来继承配置。在子Bean中写实现的属性-->
<bean id="dept04" abstract="true" class="com.zm.bean.relative.Dept"></bean>
<bean id="dept05" parent="dept04">
<property name="deptId" value="1001"/>
<property name="deptName" value="国际业务部"/>
</bean>
测试类中:
@Test
public void test01(){
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext-relative.xml");
Dept dept05 = context.getBean("dept05", Dept.class);
System.out.println(dept05);
}
运行结果:
4、并不是 元素里的所有属性都会被继承.。比如: autowire, abstract 等。也可以忽略父 Bean 的class 属性, 让子 Bean 指定自己的类, 而共享相同的属性配置. 但此时 abstract 必须设为 true
<bean id="abst" abstract="true" ></bean>
<bean id="dept05" parent="abst" class="com.zm.bean.relative.Dept">
<property name="deptId" value="1001"/>
<property name="deptName" value="国际业务部"/>
</bean>
测试类中:
@Test
public void test01(){
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext-relative.xml");
Dept dept05 = context.getBean("dept05", Dept.class);
System.out.println(dept05);
}
运行结果:
注意:这个继承关系并不是只面向对象中的继承,而是Bean配置中的继承。