spring - constructor injection and overriding parent definition of nested bean

后端 未结 4 2042
执念已碎
执念已碎 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: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:

    
       
          
             
          
       
    

    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.

提交回复
热议问题