Over a million developers have joined DZone.
Platinum Partner

Creating New Spring Beans on Demand

· Java Zone

The Java Zone is brought to you in partnership with AppDynamics. Discover how AppDynamics steps in to upgrade your performance game and prevent your enterprise from these top 10 Java performance problems.

 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


The Java Zone is brought to you in partnership with AppDynamics. AppDynamics helps you gain the fundamentals behind application performance, and implement best practices so you can proactively analyze and act on performance problems as they arise, and more specifically with your Java applications. Start a Free Trial.

Topics:

Published at DZone with permission of Jens Schauder , DZone MVB .

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}