How to inject prototype dependency in a singleton bean


As we know once the singleton bean is created all the properties object defined in it are created once. But what about special and rare case in which one of the property object needs to be created everytime the singleton object is required. for example i have put a property in a singleton object as Timestamp, which can tell me when my singleton object was accessed. For this I need to know the exact time when the object is fetched and not created.
Possible solution could be everytime the method “getInstance()” is called a new Timestamp object is created and injected into spring object.
This is also possible in Spring using look-up method injection.
Lookup method injection refers to the ability of the container to override methods on container managed beans, to return the result of looking up another named bean in the container. The lookup will typically be of a prototype bean.

public abstract class SingletonBean{
public abstract Timestamp getCurrentTime();
}


In spring.xml
< bean id="mySingleton" class="com.SingletonBean" >
< lookup-method name="getCurrentTime" bean="currentTimeBean"/ >
< / bean >
< bean id ="currentTimeBean" class="java.sql.TimeStamp" scope="prototype"/ >

It is mandatory to make currentTimeBean as prototype otherwise same instance of bean will be passed.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s