Share this page to your:
Mastodon

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”>  
        <list>  
            <bean class=”test.example.InjectedBean1″/>  
            <bean class=”test.example.InjectedBean2″/>  
            <bean class=”test.example.InjectedBean3″/>  
        </list>  
    </property>
</bean>

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”/>  
<context:annotation-config/>

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:

@Component  
public class InjectedBean1 implements InjectedBeanInterface

and in the container bean we have this:

@Autowired  
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:
infoq
stackoverflow

There’s a complete code example here

Previous Post Next Post