(八)Spring框架——Bean Defintion Inheritance

一个bean可以包含很多个配置信息,例如构造器参数,属性值,和特定容器的信息(如:初始化方法、静态工厂名称)等等。
一个child bean的定义可以从parent bean中继承配置数据。child bean可以根据需要覆盖一些属性值,或添加其他新的属性。
Spring bean的继承定义和Java class的继承没有关系,但是继承的原理是相似的。你可以定义一个parent bean作为模板,让其他的child bean来继承它的必需参数配置。

Bean的模板定义:
实际环境中你可以定义一个模板bean来供其他的child bean继承,这样可以省去很多工作。当定义一个模板bean的时候,你可以不用指定class属性,当时需要指定abstract属性值为true,就像下面:
<?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-3.0.xsd">

   <bean id="beanTeamplate" abstract="true">
      <property name="message1" value="Hello World!"/>
      <property name="message2" value="Hello Second World!"/>
      <property name="message3" value="Namaste India!"/>
   </bean>

   <bean id="helloIndia" class="com.tutorialspoint.HelloIndia" parent="beanTeamplate">
      <property name="message1" value="Hello India!"/>
      <property name="message3" value="Namaste India!"/>
   </bean>

</beans>
由于parent bean中没有指定class属性,所以这个bean是不能被实例化的,因此它被明确的标记为abstract。当一个bean被定义成这样的模板bean,那它只能作为被其他child bean继承的模板bean。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值