Spring prototype scope with autowired

Ayushi picture Ayushi · Oct 24, 2013 · Viewed 7.4k times · Source

I have a class JobListener that is listening to a queue using Spring Integration. Inside JobListener, i have an Autowired field Helper whose scope is defined as "prototype".

public class JobListener {

@Autowired
private Helper helper;

@ServiceActivator
public void receiveMessage(Message<String> message){
    helper.processMassage(message);
    }
}

Now my question is, Since the scope of Helper is defined as Protype, will i get a new instance of helper every time recieveMessage is called?

Answer

Debojit Saikia picture Debojit Saikia · Oct 24, 2013

The container only creates the singleton bean JobListener once, and thus only gets one opportunity to set the properties. The container cannot provide bean JobListener with a new instance of bean Helper every time one is needed.

One solution to this problem is to use Method Injection: Lookup method injection is the ability of the container to override methods on container managed beans, to return the lookup result for another named bean in the container. To implement this solution, re-define the JobListener class as this:

public abstract class JobListener {

@ServiceActivator
public void receiveMessage(Message<String> message){
    Helper helper = createHelper();
    helper.processMassage(message);
    }

protected abstract Helper createHelper();
}

The Spring Framework will generate a dynamic subclass of JobListener that will override the createHelper method to provide a new instance of Helper every time it is requested for.

You need to define the name of lookup-method name in the JobListener bean definition:

<bean id="helper" class="x.y.Helper" scope="prototype">
...
</bean>

<bean id="jobListener" class="x.y.JobListener">
<lookup-method name="createHelper" bean="helper"/>
</bean>

With the above configurations in place, every time you execute

Helper helper = createHelper();

it will return you a new instance of Helper.