抽象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中的子類實例完全可以當成父類實例使用。