Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring XML inner bean question

Tags:

I have created a spring bean that contains a list of other beans, like so:

<bean name="InventoryManager" class="InvManager">
  <property name="slots">
    <bean class="HeadSlot" />
    <bean class="ShoulderSlot" />
    <!-- ... -->
  </property>
</bean>

The problem, though, is that elsewhere I have used an @Autowired annotation in another class to grab a list of all beans implementing a certain interface that some of these inner beans implement, like so:

@Autowired
public void registerInventoryHandlers( List<InvSlot> slots ) {
    //... do some setup stuff with beans that implement the InvSlot interface.
}

The problem here is that apparently the "inner beans" defined in XML are not part of the @Autowired list. However, giving all of these slot beans names and then referencing them from the XML seems unnecessary and ugly.

Is there a way to define a bean inside another bean, but not be an "inner" bean? Or is there a better way to handle this design?

like image 208
Brandon Yarbrough Avatar asked Aug 12 '09 06:08

Brandon Yarbrough


1 Answers

Beans defined inside other beans are, by definition, "inner" beans. The docs say:

Inner beans are always anonymous and they are always scoped as prototypes. Please also note that it is not possible to inject inner beans into collaborating beans other than the enclosing bean.

edited to remove stuff that was poorly thought out, irrelevent or just plain wrong

I suggest that rather than autowiring the list of InvSlot beans, you autowire yourself with the InvManager bean instead. You can then ask the InvManager for the list of InvSlot beans, while keeping your list of inner bean definitions inside the InvManager definition.

like image 148
skaffman Avatar answered Nov 21 '22 10:11

skaffman