Tuesday, March 10, 2015

Method level Injection with spring (Injecting prototype model in to singleton model)

When we want to inject prototype model object into singleton object we will be having an issue.

How we can achieve this in spring? we have a concept calling method injection. All beans in the spring's are singleton by default,
meaning spring instantiates them during context creation,caches them in context, when ever it needed it will load from cache,
if you make a particular object scope as prototype and you want to inject this object into other singleton object the actual problem arrives.

public class Singleton {

    private Prototype prototype;

    public Singleton(Prototype prototype) {

        this.prototype = prototype;
    }

    public void doSomething() {

        prototype.foo();
    }

    public void doSomethingElse() {

        prototype.bar();
    }
}

The below code displays the correct code of method injection:

public abstract class Singleton {

    protected abstract Prototype createPrototype();

    public void doSomething() {

        createPrototype().foo();
    }

    public void doSomethingElse() {

        createPrototype().bar();
    }
}

As you noticed, code doesn’t specify the createPrototype() implementation. This responsibility is delegated to Spring, hence the following needed configuration:

<bean id="prototype" class="ch.frankel.blog.Prototype" scope="prototype">

<bean id="singleton" class="sample.MySingleton">
  <lookup-method name="createPrototype" bean="prototype">
</lookup-method></bean></bean>





No comments: