来自http://my.oschina.net/u/1984151/blog/295996
在基于spring框架开发的项目中,如果有多个bean都是一个类的实力,如配置多个数据源时,大部分配置的属性都一样,只有少部分不一样,经常是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
=
"父参数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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
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函数输出:
1
2
3
4
|
父参数
1
父参数
2
子参数
1
父参数
2
|