I’m creating a web app using Spring 3 and would like to harness the power of the Spring Expression Language but have run into a problem. I need to set the value of a property on one of my beans to the result of a method call on another bean. I know I can do this but the issue is that the result of that method call may change after the bean is initialized and I need that property to reflect the change. For instance:
<beans>
...
<bean name="guestList" class="java.util.ArrayList"></bean>
<bean name="party" class="some.custom.class.Party">
<property name="numberOfGuests" value="#{guestList.size()}" />
</bean>
...
</beans>
From what I can tell, the numberOfGuests field is set the first time the party field is accessed. But after the party field is accessed, the number of guests may change and I need the numberOfGuests field to reflect that. Is there a way to reinitialize the numberOfGuests field within my app whenever I need the value updated?
This is just an example and accessing the guestList bean directly will not work for my specific situation.
if you set your scope to prototype then each time Spring loads your bean it should recalculate the guest list size:
So,
partybecomes prototype butguestListcan stay a singleton (which is the default scope).There’s a catch though: if you have another bean, like
partyHost(which is a singleton), and it gets injected withparty(which is a prototype),partyHostwill never get another instance ofparty, sincepartyHostis a singleton, and only gets dependencies injected into it once. So for this to work, all of your beans that need the updated guest list size, and all of the beans that reference them, etc. must be prototypes too.Either that, or you’d have to ask Spring directly via their API. If you use the API, you could call it any time you want and get a new instance of the prototype bean, and therefore the updated guest list size.
However it’s better to avoid the Spring API if you can. Typically developers don’t want to be coupled to a DI framework.