五、深入理解容器中的Bean

抽象Bean和子Bean

把多个<bean.../>配置中相同的信息提取出来,集中成配置模板。
抽象Bean只是配置信息的模板,指定abstract="true"即可阻止Spring实例化该Bean,因此抽象Bean可以不指定class属性。<bean.../>元素指定parent属性即可指定该Bean是一个子Bean,parent属性指定该Bean所继承父Bean的id。
子Bean不能从父Bean继承如下属性:depends-on、 autowired、 singleton、 scope、 lazy-init。

beans.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"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd" >
     
       <!-- 定义抽象Bean,指定abstract="true" -->
      <bean id="parentTemple" abstract="true">
         <property name="name" value="it"/>
         <property name="axe" value="steelAxe"/>
      </bean>
      
      <!-- 子Bean继承父Bean -->
      <bean id="child1" class="inter.Child" parent="parentTemple"/>
      <bean id="child2" class="inter.Child" parent="parentTemple"/>
</beans>

当子Bean拥有和父Bean相同的配置信息时,子Bean的配置信息取胜。

Bean继承和Java继承的区别:

  • Spring中的子Bean和父Bean可以是不同类型,而Java中的子类是一种特殊的父类。
  • Spring中的Bean的继承是实例之间的关系,主要表现为参数值得延续;而Java中的继承是类之间的关系,主要表现为方法、属相的延续。
  • Spring中的子Bean不能作为父Bean使用,不具备多态性;Java中的子类实例完全可以当成父类实例使用。
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 136,288评论 19 139
  • Spring Boot 参考指南 介绍 转载自:https://www.gitbook.com/book/qbgb...
    毛宇鹏阅读 47,227评论 6 342
  • 文章作者:Tyan博客:noahsnail.com 3.4 Dependencies A typical ente...
    SnailTyan阅读 9,825评论 2 7
  • 1. Java基础部分 基础部分的顺序:基本语法,类相关的语法,内部类的语法,继承相关的语法,异常的语法,线程的语...
    子非鱼_t_阅读 33,799评论 18 399
  • 啊哈哈哈哈哈哈哈哈哈 你们去过光棍节吧 我过校庆!我桂工六十岁啦 无心插柳柳成荫 写了个三行情书还选上了 人缘好...
    狄欢大人阅读 1,859评论 0 0

友情链接更多精彩内容