Monday, October 5, 2009

On the Importance of Scope


Those of you who know me may think I'm going to harp on about JavaScript again. No, this time it's about Spring.

Spring is good for wiring up your beans with any services it may need. You do this in XML traditionally, by declaring beans:


<bean id="lieschke">
<property name="doc" value="true"></property>
</bean>

You can then use this bean inside other beans:


<bean id="webArchitecting">
<property name="architect" ref="lieschke"></property>
</bean>


The problem is that with this bean declaration is that Spring, by default, will only make one instance of the lieschke bean. This is a problem if you need your bean to not be a singleton; perhaps if you give it a database connection which you wouldn't want it to hang onto for a long time.

The solution is the scope property. Using this property, we can say that we want a new instance every time:

<bean id="lieschke" scope="prototype">
<property name="doc" value="true"></property>
</bean>

All very easy and all, but why isn't it this by default?