spring框架学习笔记(五)

继承bean配置

同一类型,如果有多个bean需要配置,且大多数属性相同,则可以使用parent属性来实现复用。

例子配置如下:

 其中Bean: student_gfc  是通过parent属性复用的Bean:student_pf的值,因此class与studentNo都与student_pf一致。

    <bean id="student_pf" class="com.pfSoft.autowire.beans.Student" p:name="pf" p:studentNo="001"></bean>
    <bean id="student_ldh" class="com.pfSoft.autowire.beans.Student" p:name="刘德华" p:studentNo="002"></bean>
    <bean id="student_gfc"  p:name="郭富城" parent="student_pf"></bean>

 测试代码如下:

@Test
    public void testParent() {
        Student student=    (Student) applicationContext.getBean("student_pf");
        System.out.println(student.toString());
        
        Student student1=    (Student) applicationContext.getBean("student_ldh");
        System.out.println(student1.toString());
        
        Student student2=    (Student) applicationContext.getBean("student_gfc");
        System.out.println(student2.toString());
    }

 输出为:

Student [studentNo=1, name=pf]
Student [studentNo=2, name=刘德华]
Student [studentNo=1, name=郭富城]

其中子bean可以重写覆盖父bean的属性值。另外也可以将父bean配置成专用的模板,即抽象bean。只需要添加abstract=true即可。如下:

	<bean id="student_pf" class="com.pfSoft.autowire.beans.Student" p:name="pf" p:studentNo="001" abstract="true"></bean>

而抽象bean不能产生实例,只能作为配置模板使用。感觉有点类似于抽象类的感觉,同样不能被实例化。

原文地址:https://www.cnblogs.com/falcon-fei/p/5423072.html