bean之间的继承和依赖关系

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_38409944/article/details/82668219

继承关系:

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>

猜你喜欢

转载自blog.csdn.net/qq_38409944/article/details/82668219