简体   繁体   中英

spring parent child configuration (abstract bean)

I have a question about spring's bean.

There are parent class Parent with constructor (without any setters).

class abstract Parent{
    procected Something someth;

    public Parent(Object1 obj1 , Object2 obj2 , Object3 obj3){
        someth.setObj1(obj1);
        someth.setObj2(obj2);
        someth.setObj3(obj3);
    }
}

class Child extends Parent implements SoneInterface{

     public Parent(Object1 obj1 , Object2 obj2 , Object3 obj3){
          supper(obj1,obj2,obj3);
     }

     public void methodFormSoneInterface(){
          ....................
          someth.do();
     }
}

Object1 obj1 - it the same object for any children's instance. Object2 obj2 , Object3 obj3 -can be bifferent for any instances

If I had setter for parent (I can't change it) , I could declare abstract bean ,set Object1 obj1 for it and after that I can use it as abstract bean (set only obj2 and obj3 reference/value).

Is there any chance to configure in xml parent/abstract bean with obj1 param , any define right values (set only obj2 and obj3) for children?

Thanks

It is possible to partially construct an abstract bean. you may want to try this.

<bean id="parentBean" abstract="true">
    <property name="obj1" ref="obj1Ref" /> 
</bean>

<bean id="childBean" parent="parentBean" class="com.childClass">
    <property name="obj2" ref="obj2Ref" /> 
    <property name="obj3" ref="obj3Ref" /> 
</bean>

It should work like this, where the first argument in the constructor is the one you want it set at the parent level and the other two can be set at the child level:

<bean id="parent" class="com.foo.bar.Parent" abstract="true">
    <constructor-arg index="0" value="123" />
</bean>

<bean id="child1" class="com.foo.bar.Child" parent="parent">
    <constructor-arg index="1" value="234" />
    <constructor-arg index="2" value="456" />
</bean>

<bean id="child2" class="com.foo.bar.Child" parent="parent">
    <constructor-arg index="1" value="aaa" />
    <constructor-arg index="2" value="bbb" />
</bean>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM