Over a million developers have joined DZone.

Creating New Spring Beans on Demand

· Java Zone

Microservices! They are everywhere, or at least, the term is. When should you use a microservice architecture? What factors should be considered when making that decision? Do the benefits outweigh the costs? Why is everyone so excited about them, anyway?  Brought to you in partnership with IBM.

 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


Discover how the Watson team is further developing SDKs in Java, Node.js, Python, iOS, and Android to access these services and make programming easy. Brought to you in partnership with IBM.

Topics:

Published at DZone with permission of Jens Schauder, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

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

{{ parent.tldr }}

{{ parent.urlSource.name }}