Spring Bean Identity Crisis

I recently ran into, again, a problem with Spring Beans not having an id. While using Spring XML configuration files, the id attribute is optional. However, if the Spring configuration file in question is imported from multiple places, the Bean will be created multiple times, once for each import.

For a very contrived example, say you have file A.xml:

<beans>
    <bean class=”com.example.JobScheduler”>
        <property name=”howOften” value=”10″>
    </bean>
</beans>

And file B.xml:

<beans>
    <import resource=”classpath:A.xml” />
</beans>

And file applicationContext.xml:

<beans>
    <import resource=”classpath:A.xml” />
    <import resource=”classpath:B.xml” />
</beans>

You would end up with TWO JobScheduler instances, each one happily kicking off jobs every 10 somethings.

This is of course not a problem for a Bean that does not “do” anything. But for a Bean that creates its own threads, runs in the background, etc, this can be a definite problem.

So, remember, don’t leave your Spring Beans wondering who they are, give them an ID, so they only get created once.

Leave a Reply