在基於spring框架開發的項目中,若是有多個bean都是一個類的實力,如配置多個數據源時,大部分配置的屬性都同樣,只有少部分不同,常常是copy上一個的定義,而後修改不同的地方。其實spring bean定義也能夠和對象同樣進行繼承。java
示例以下:spring
<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不會被建立,相似於於抽象類。其中testBeanChild一、testBeanChild2繼承了testBeanParent、,其中testBeanChild2從新對param1屬性進行了配置,所以會覆蓋testBeanParentapp
對param1屬性屬性的配置。框架
代碼以下:函數
TestBean
this
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:spa
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函數輸出:code
父參數1 父參數2 子參數1 父參數2