Sunday, 3 January 2010

Autowiring Spring collections

The problem: an undefined number of classes that need to be added to a collection which is then injected into a class. Assume Springframeworks for the injection.

The obvious thing to do is this:

<bean id="ContainerBean" class="test.example.ContainerBean">
<property name="MyList">
<bean class="test.example.InjectedBean1"/>
<bean class="test.example.InjectedBean2"/>
<bean class="test.example.InjectedBean3"/>

But that means every time I add a class I have to change the wiring.

Instead, using Spring 2.5 we can do this:

<context:component-scan base-package="test.example"/>

yes, apart from the usual stuff at the top, that's all I need in this file. The injected beans all have this in their declaration:

public class InjectedBean1 implements InjectedBeanInterface

and in the container bean we have this:

private List m_myList;

...along with the usual getter and setter, of course.

With that in place Spring happily finds the relevant classes and adds them to the collection. If I add one more injected bean then I just have to remember to add the @Component annotation to it and it will end up in the collection. I use this pattern quite a lot these days. Often other people are implementing the injected beans and I need to keep the list of things they have to remember as small as possible. This approach helps.

Spring is happy enough with a typed List or an array, so my bean implementers don't need to know what they are being injected into. In fact in my current project these injected beans are being generated by some other software. I can customise that to add the annotation automatically, but I don't have to figure out how to automatically edit the beans file.

References which helped me get there:

There's a complete code example on my website
Post a Comment