【Spring学习笔记-5】Spring中的抽象bean以及bean继承

概要:

Spring配置文件中,当若干个bean的配置内容大部分都是相同的,只有少部分是不同的时候,如果按照普通的方式去配置这些bean,实际有太多的重复内容被配置。
可以通过抽象bean来实现简化。
抽象bean类似java中的父类,把公有的配置写在抽象bean中,可以实现简化。


具体操作:

通过指定abstract=“true”,来声明一个bean为抽象bean,可被继承;

  1. <?xml version="1.0" encoding="GBK"?>
  2. <beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3. xmlns="http://www.springframework.org/schema/beans"
  4. xsi:schemaLocation="http://www.springframework.org/schema/beans
  5. http://www.springframework.org/schema/beans/spring-beans-4.0.xsd">
  6. <!-- 定义Axe实例 -->
  7. <bean id="steelAxe" class="org.crazyit.app.service.impl.SteelAxe"/>
  8. <!-- 指定abstract="true"定义抽象Bean -->
  9. <bean id="personTemplate" abstract="true">
  10. <property name="name" value="crazyit"/>
  11. <property name="axe" ref="steelAxe"/>
  12. </bean>
  13. <!-- 通过指定parent属性指定下面Bean配置可从父Bean继承得到配置信息 -->
  14. <bean id="chinese" class="org.crazyit.app.service.impl.Chinese"
  15. parent="personTemplate"/>
  16. <bean id="american" class="org.crazyit.app.service.impl.American"
  17. parent="personTemplate"/>
  18. </beans>

上面的配置与下面的等同

  1. <?xml version="1.0" encoding="GBK"?>
  2. <beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3. xmlns="http://www.springframework.org/schema/beans"
  4. xsi:schemaLocation="http://www.springframework.org/schema/beans
  5. http://www.springframework.org/schema/beans/spring-beans-4.0.xsd">
  6. <!-- 定义Axe实例 -->
  7. <bean id="steelAxe" class="org.crazyit.app.service.impl.SteelAxe"/>
  8. <!-- 通过指定parent属性指定下面Bean配置可从父Bean继承得到配置信息 -->
  9. <bean id="chinese" class="org.crazyit.app.service.impl.Chinese">
  10. <property name="name" value="crazyit"/>
    <property name="axe" ref="steelAxe"/>
  11. <bean/>

  12. <bean id="american" class="org.crazyit.app.service.impl.American">
  13. <property name="name" value="crazyit"/>
    <property name="axe" ref="steelAxe"/>
    <bean/>
  14. </beans>







原文地址:https://www.cnblogs.com/ssslinppp/p/4381304.html