spring中使用parent属性来减少配置

来自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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值