Spring配置文件parent與abstract
其實在基于spring框架開發(fā)的項目中,如果有多個bean都是一個類的實例,如配置多個數(shù)據(jù)源時,大部分配置的屬性都一樣,只有少部分不一樣。
這樣的話在配置文件中可以配置和對象一樣進行繼承。
例如
1
2
3
4
5
6
7
8
|
< bean id = "testParent" abstract = "true" class = "com.bean.TestBean" > < property name = "param1" value = "父參數(shù)1" /> < property name = "param2" value = "父參數(shù)2" /> </ bean > < bean id = "testBeanChild1" parent = "testParent" /> < bean id = "testBeanChild2" parent = "testParent" > < property name = "param1" value = "子參數(shù)1" /> </ bean > |
其中 abstract="true" 的配置表示:此類在Spring容器中不會生成實例。
parent="testBeanParent" 代表子類繼承了testBeanParent,會生成具體實例,在子類Bean中配置會覆蓋父類對應(yīng)的屬性。
spring使用parent屬性來減少配置
在基于spring框架開發(fā)的項目中,如果有多個bean都是一個類的實力,如配置多個數(shù)據(jù)源時,大部分配置的屬性都一樣,只有少部分不一樣,經(jīng)常是copy上一個的定義,然后修改不一樣的地方。其實spring bean定義也可以和對象一樣進行繼承。
示例如下:
1
2
3
4
5
6
7
8
|
< bean id = "testBeanParent" abstract = "true" class = "com.wanzheng90.bean.TestBean" > < property name = "param1" value = "父參數(shù)1" /> < property name = "param2" value = "父參數(shù)2" /> </ bean > < bean id = "testBeanChild1" parent = "testBeanParent" /> < bean id = "testBeanChild2" parent = "testBeanParent" > < property name = "param1" value = "子參數(shù)1" /> </ bean > |
testBeanParent是父bean,其中abstract=“true”表示testBeanParen不會被創(chuàng)建,類似于于抽象類。其中testBeanChild1、testBeanChild2繼承了testBeanParent、,其中testBeanChild2重新對param1屬性進行了配置,因此會覆蓋testBeanParent
對param1屬性屬性的配置。
代碼如下:
TestBean
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
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:
1
2
3
4
5
6
7
8
9
10
11
12
13
|
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函數(shù)輸出:
父參數(shù)1
父參數(shù)2
子參數(shù)1
父參數(shù)2
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持服務(wù)器之家。
原文鏈接:https://blog.csdn.net/wqc19920906/article/details/82353469