Creating New Spring Beans on Demand
We lately had a little Spring related challenge in our application at work. We had a singleton bean (TheClient) that on every call of a method needed a group of other beans. These beans (TheService) unfortunately where stateful and couldn’t be reused on the next call. So they had to be recreated every time.
Not a big deal we thought at first, nothing forces us to use Spring, so we just created the bean using … drum roll … new.
This works fine until you need something from your Spring context. Maybe another bean or something provided via AOP. Of course you can make your bean ApplicationContextAware and look it up using the getBean method on the ApplicationContext.
But this really negates the idea of dependency injection and typically is a sign something is messed up. But how to do it properly? I was a little surprised that my google searches didn’t turn up anything useful. So I brought my question to the place where every IT question belongs these days: Stackoverflow. Sure enough Oliver Gierke, whom I know from him talking at our local java user group pointed me to the solution.
TheClient provides an abstract method returning the required bean:
public abstract TheService createService()
If configured correctly Spring will provide the implementation for the method.
<bean id="theService" class="TheService" scope="prototype" /> <bean class="TheClient"> <lookup-method name="createService" bean="theService" /> </bean>
Now you can call createService any time you need a fresh Spring managed instance of TheService
(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)