bean之间的继承和依赖关系

继承关系:

bean配置之间的继承 使用bean的parent属性,指定继承哪个bean的配置
注意:
可以继承父Bean的属性配置,也可以覆盖从父Bean继承过来的配置

xml文件配置:

<bean id="helloSet1" class="hello.Hello" p:name="name" p:numberInt="12" p:numberDouble="3.14">
    </bean>
    <bean id="helloSet2" parent="helloSet1">
    </bean>
Hello person = (Hello) applicationContext.getBean("helloSet2");
System.out.println(person);

输出:

Hello{name='name', numberInt=12, numberDouble=3.14}

abstract属性:

注意:
bean的abstract属性为true的bean是不能被IOC实例化的,只能用来被继承配置: 父bean就是一个配置模板.

XML配置文件:

<bean id="helloSet1" class="hello.Hello" p:name="name" p:numberInt="12" p:numberDouble="3.14" abstract="true">
    </bean>
    <bean id="helloSet2" parent="helloSet1">
    </bean>

测试:

Hello person = (Hello) applicationContext.getBean("helloSet1");
        System.out.println(person);
输出:
        Error creating bean with name 'helloSet1': Bean definition is abstract

Hello person = (Hello) applicationContext.getBean("helloSet2");
System.out.println(person);
输出:
        Hello{name='name', numberInt=12, numberDouble=3.14}

并不是所有父bean的所有属性都会被继承:比如autowire ,abstract等

可以忽略父bean的class属性,让子brean指定自己的类,而共享相同的属性配置,但是此时abstract必须设置为true
举例:

    <bean id="helloSet1"  p:name="name" p:numberInt="12" p:numberDouble="3.15" abstract="true">
    </bean>
    <bean id="helloSet2" class="hello.Hello" parent="helloSet1">

依赖Bean设置

通过depends-on 设置Bean前置依赖的Bean,牵制依赖的Bean会在本Bean实例化前创建好
如果前置依赖于多个Bean,则可以通过都好 空格的方式配置Bean的名称

    <bean id="helloSet1" class="hello.Hello"  p:name="name" p:numberInt="12" p:numberDouble="3.15">
    </bean>
    <bean id="helloSet2" class="hello.Hello"  p:name="name" p:numberInt="12" p:numberDouble="3.15">
    </bean>
    <bean id="helloSet3" parent="helloSet1" depends-on="helloSet1 helloSet2">
    </bean>
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值