在基於spring框架開發的項目中,如果有多個bean都是一個類的實力,如配置多個數據源時,大部分配置的屬性都一樣,只有少部分不一樣,經常是copy上一個的定義,然後修改不一樣的地方。其實spring bean定義也可以和對象一樣進行繼承。
示例如下:
<bean id="testBeanParent" abstract="true" class="com.wanzheng90.bean.TestBean">
<property name="param1" value="父參數1"/>
<property name="param2" value="父參數2"/>
</bean>
<bean id="testBeanChild1" parent="testBeanParent"/>
<bean id="testBeanChild2" parent="testBeanParent">
<property name="param1" value="子參數1"/>
</bean>
testBeanParent是父bean,其中abstract=“true”表示testBeanParen不會被創建,類似於於抽象類。其中testBeanChild1、testBeanChild2繼承了testBeanParent、,其中testBeanChild2重新對param1屬性進行了配置,因此會覆蓋testBeanParent
對param1屬性屬性的配置。
代碼如下:
TestBean
public class TestBean {
private String param1;
private String param2;
public String getParam1() {
return param1;
}
public void setParam1(String param1) {
this.param1 = param1;
}
public String getParam2() {
return param2;
}
public void setParam2(String param2) {
this.param2 = param2;
}
}
App:
public class App
{
public static void main( String[] args )
{
ApplicationContext context = new ClassPathXmlApplicationContext("classpath:spring-context.xml");
TestBean testBeanChild1 = (TestBean) context.getBean("testBeanChild1");
System.out.println( testBeanChild1.getParam1());
System.out.println( testBeanChild1.getParam2());
TestBean testBeanChild2 = (TestBean) context.getBean("testBeanChild2");
System.out.println( testBeanChild2.getParam1());
System.out.println( testBeanChild2.getParam2());
}
}
app main函數輸出:
父參數1
父參數2
子參數1
父參數2