Spring Bean在XML配置中的父子继承

与Java类的继承相似,Spring框架也提供了Spring Bean的属性的继承。也就是说,有的Spring Bean是抽象的,可以被继承;有的Spring Bean可以指定继承的父Spring Bean。这时候,抽象的Spring Bean也可以被称为模板,供定义具体的业务逻辑Spring Bean时使用。

这可以通过Spring框架的XML配置文件实现,下面以两个例子进行说明。

1.没有实现类的抽象父Spring Bean

<bean id="inheritedTestBeanWithoutClass" abstract="true">
    <property name="name" value="parent"/>
    <property name="age" value="1"/>
</bean>

<bean id="inheritsWithClass" class="org.springframework.beans.DerivedTestBean" parent="inheritedTestBeanWithoutClass" init-method="initialize">
    <property name="name" value="override"/>
    <!-- age will inherit the value of 1 from the parent bean definition-->
</bean>

如代码所示,抽象父Spring Bean没有对应的具体Java类,这时继承的子Spring Bean必须对应一个实现类。

通常,被继承的父Spring Bean必须使用属性abstract="true"进行标识。继承父Spring Bean的子Spring Bean,需要使用属性parent="..."指定继承的父Spring Bean。

此外,子Spring Bean可以补充定义新的属性,也可以覆盖父子Spring Bean定义的属性。


2.有实现类的抽象父Spring Bean

<bean id="inheritedTestBean" abstract="true" class="org.springframework.beans.TestBean">
    <property name="name" value="parent"/>
    <property name="age" value="1"/>
</bean>

<bean id="inheritsWithDifferentClass" class="org.springframework.beans.DerivedTestBean" parent="inheritedTestBean" init-method="initialize">
    <property name="name" value="override"/>
    <!-- the age property value of 1 will be inherited from parent -->
</bean>

<bean id="inheritsWithSameClass" parent="inheritedTestBean" init-method="initialize">
    <property name="name" value="override"/>
    <!-- the age property value of 1 will be inherited from parent -->
</bean>

如代码所示,抽象父Spring Bean对应一个Java类,这时继承的子Spring Bean可以有另外的Java类对应,也可以没有对应的Java类。


Spring Bean的父子继承主要是为了统一定义Spring Bean的公共属性、作业范围scope,并避免了冗余和修改的繁琐。


  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值