此版本仍在开发中,尚未被视为稳定版本。对于最新的稳定版本,请使用 Spring Framework 6.2.0spring-doc.cadn.net.cn

Bean 定义继承

一个 bean 定义可以包含很多配置信息,包括构造函数 参数、属性值和特定于容器的信息,例如初始化 method、静态工厂方法名称等。子 Bean 定义继承 来自父定义的 configuration 数据。子定义可以覆盖一些 值或根据需要添加其他值。使用父 Bean 定义和子 Bean 定义可以节省很多 的打字。实际上,这是一种模板形式。spring-doc.cadn.net.cn

如果您使用ApplicationContext以编程方式接口,子 Bean 定义由ChildBeanDefinition类。大多数用户不工作 与他们在这个层面上。相反,它们在类中以声明方式配置 bean 定义 例如ClassPathXmlApplicationContext.使用基于 XML 的配置时 元数据,您可以使用parent属性 指定父 Bean 作为此属性的值。以下示例显示了如何作 为此,请执行以下作:spring-doc.cadn.net.cn

<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">  (1)
	<property name="name" value="override"/>
	<!-- the age property value of 1 will be inherited from parent -->
</bean>
1 请注意parent属性。

子 Bean 定义使用父定义中的 Bean 类(如果没有 指定,但也可以覆盖它。在后一种情况下,子 Bean 类必须是 与 Parent 兼容(即,它必须接受 Parent的 Property 值)。spring-doc.cadn.net.cn

子 Bean 定义继承 scope、constructor argument 值、property 值和 method 覆盖父级,并可选择添加新值。任何范围、初始化 method、destroy method 或static您指定的出厂设置方法 覆盖相应的父设置。spring-doc.cadn.net.cn

其余设置始终取自子定义:depends on, autowire 模式、依赖关系检查、Singleton 和 Lazy init。spring-doc.cadn.net.cn

前面的示例通过使用 这abstract属性。如果父定义未指定类,则显式 将父 Bean 定义标记为abstract是必需的,如下例所示 显示:spring-doc.cadn.net.cn

<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 不能单独实例化,因为它不完整,并且是 也显式标记为abstract.当定义为abstract是的 只能用作纯模板 bean 定义,用作 子定义。尝试使用这样的abstract父 Bean 本身,通过引用 作为另一个 bean 的 ref 属性或执行显式getBean()call 替换为 父 Bean ID 返回错误。同样,容器的内部preInstantiateSingletons()method 忽略定义为 抽象。spring-doc.cadn.net.cn

ApplicationContext默认情况下,预实例化所有单例。因此,它是 重要的是(至少对于单例 bean),如果你有一个(父)bean 定义 它仅打算用作模板,并且此定义指定了一个类,则 必须确保将 abstract 属性设置为 true,否则应用程序 context 实际上会(尝试)预先实例化abstract豆。