spring - constructor injection and overriding parent definition of nested bean

后端 未结 4 2043
执念已碎
执念已碎 2021-02-06 03:53

I\'ve read the Spring 3 reference on inheriting bean definitions, but I\'m confused about what is possible and not possible.

For example, a bean that takes a collaborato

相关标签:
4条回答
  • 2021-02-06 04:08

    Have you thought of using a factory instead?

    You can config beans to have a factory and you could encode the varying parameters in the factory creation...

    0 讨论(0)
  • 2021-02-06 04:12

    Your example will not work as specified, because the nested bean definition has no class or parent specified. You'd need to add more information, like this:

    <bean name="beanService13" parent="beanService12">
       <constructor-arg index="0">
          <bean parent="beanBaseNested">
             <constructor-arg index="0" value="13"/>
          </bean>
       </constructor>
    

    Although I'm not sure if it's valid to refer to nested beans by name like that.

    Nested bean definitions should be treated with caution; they can quickly escalate into unreadability. Consider defining the inner beans as top-level beans instead, which would make the outer bean definitions easier to read.

    As for the child beans needing to know the constructor index of the parent bean, that's a more basic problem with Java constructor injection, in that Java constructor arguments cannot be referred to by name, only index. Setter injection is almost always more readable, at the cost of losing the finality of constructor injection.

    A custom schema is always an option, as you mentioned, although it's a bit of a pain to set up. If you find yourself using this pattern a lot, it might be worth the effort.

    0 讨论(0)
  • 2021-02-06 04:14

    To expand on the factory pattern from Patrick: you can use a prototype bean to get pre-wired dependencies:

    <bean id="protoBean" scope="prototype">
     <property name="dependency1" ref="some bean" />
     <property name="dependency2" ref="some other bean" />
     ...
    </bean>
    

    Now, this works best if you use setter injection (rather than constructor arguments), i'm not sure you can even do it you require constructor args.

    public class PrototypeConsumingBean implements ApplicationContextAware {
    
     public void dynmicallyCreateService(String serviceParam) {
       // creates a new instance because scope="prototype"
       MyService newServiceInstance = (MyService)springContext.getBean("protoBean");
       newServiceInstance.setParam(serviceParam);
       newServiceInstance.mySetup();
       myServices.add(newServiceInstance);
     }
    
     public void setApplicationContext(ApplicationContext ctx) {
      m_springContext = ctx;
     }
    }
    
    0 讨论(0)
  • 2021-02-06 04:27

    I'm not entirely sure what you are trying to achieve. I don't think you can achieve exactly what you want without creating your own custom schema (which is non-trivial for nested structures), but the following example is probably pretty close without doing that.

    First, define an abstract bean to use as a template for your outer bean (my example uses a Car as the outer bean and an Engine as the inner bean), giving it default values that all other beans can inherit:

    <bean id="defaultCar" class="Car" abstract="true">
        <property name="make" value="Honda"/>
        <property name="model" value="Civic"/>
        <property name="color" value="Green"/>
        <property name="numberOfWheels" value="4"/>
        <property name="engine" ref="defaultEngine"/>
    </bean>
    

    Since all Honda Civics have the same engine (in my world, where I know nothing about cars), I give it a default nested engine bean. Unfortunately, a bean cannot reference an abstract bean, so the default engine cannot be abstract. I've defined a concrete bean for the engine, but mark it as lazy-init so it will not actually be instantiated unless another bean uses it:

    <bean id="defaultEngine" class="Engine" lazy-init="true">
        <property name="numberOfCylinders" value="4"/>
        <property name="volume" value="400"/>
        <property name="weight" value="475"/>
    </bean>
    

    Now I can define my specific car, taking all the default values by referencing the bean where they are defined via parent:

    <bean id="myCar" parent="defaultCar"/>
    

    My wife has a car just like mine, except its a different model (again, I know nothing about cars - let's assume the engines are the same even though in real life they probably are not). Instead of redefining a bunch of beans/properties, I just extend the default car definition again, but override one of its properties:

    <bean id="myWifesCar" parent="defaultCar">
        <property name="model" value="Odyssey"/>
    </bean>
    

    My sister has the same car as my wife (really), but it has a different color. I can extend a concrete bean and override one or more properties on it:

    <bean id="mySistersCar" parent="myWifesCar">
        <property name="color" value="Silver"/>
    </bean>
    

    If I liked racing minivans, I might consider getting one with a bigger engine. Here I extend a minivan bean, overriding its default engine with a new engine. This new engine extends the default engine, overriding a few properties:

    <bean id="supedUpMiniVan" parent="myWifesCar">
        <property name="engine">
            <bean parent="defaultEngine">
                <property name="volume" value="600"/>
                <property name="weight" value="750"/>
            </bean>
        </property>
    </bean>
    

    You can also do this more concisely by using nested properties:

    <bean id="supedUpMiniVan" parent="myWifesCar">
        <property name="engine.volume" value="600"/>
        <property name="engine.weight" value="750"/>
    </bean>
    

    This will use the "defaultEngine". However, if you were to create two cars this way, each with different property values, the behavior will not be correct. This is because the two cars would be sharing the same engine instance, with the second car overriding the property settings set on the first car. This can be remedied by marking the defaultEngine as a "prototype", which instantiates a new one each time it is referenced:

    <bean id="defaultEngine" class="Engine" scope="prototype">
        <property name="numberOfCylinders" value="4"/>
        <property name="volume" value="400"/>
        <property name="weight" value="475"/>
    </bean>
    

    I think this example gives the basic idea. If your data structure is complex, you might define multiple abstract beans, or create several different abstract hierarchies - especially if your bean hierarchy is deeper than two beans.

    Side note: my example uses properties, which I believe are much clearer to understand, both in Spring xml and in Java code. However, the exact same technique works for constructors, factory methods, etc.

    0 讨论(0)
提交回复
热议问题