spring支持Bean的继承

原文:
http://static.springsource.org/spring/docs/2.5.x/reference/beans.html#beans-child-bean-definitions

Bean的继承和类的继承一样,都是为了减少重复键入:父Bean里的属性可被子Bean自动继承,在写子Bean时就不用再次键入这些属性了。

当然,子Bean可以覆盖父Bean的属性

最后,父Bean还可以做成abstract的。抽象的父Bean可以不与任何java类绑定

<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>

不过,子Bean并不会继承父Bean的所有特性。文档说: The remaining settings will always be taken from the child definition: depends on, autowire mode, dependency check, singleton, scope, lazy init.

Leave a Comment

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.