Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

SPRING - Sharing singleton with prototype - Possible?

 
Venkataramanan Amirthalingam
Greenhorn
Posts: 20
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
All,

I have a requirement where two business classes should share the same value object. And these two business classes should be instantiated one per request and value object is common for both these.

<bean id="bus1" class="com.foo.Business1" scope="prototype">
<property name="account" ref="acct"/>
</bean>
<bean id="bus2" class="com.foo.Business2" scope="prototype">
<property name="account" ref="acct"/>
</bean>
<bean name="acct" class="com.foo.Account" scope="singleton">
</bean>

I need this acct to be singleton for bus1 and bus2 instances and not for entire IOC container. In this way, when a user logs on, bus1 and bus2 will share the same acct. And for another user, a different acct instance has to be created, but shared between bus1 and bus2.

Is this possible in Spring or should i do it programmatically?

Kindly help.

Regards,
venkat
 
Mark Spritzler
ranger
Sheriff
Posts: 17278
6
IntelliJ IDE Mac Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes, it is possible. In the case of a Prototype getting injected a Singleton, you don't have to do anything. As far as a Prototype being injected into the Singleton. Then you just implement the ApplicationContextAware interface. Then your Singleton will get a reference to the ApplicationContext, and you can just call getBean() on it in your Singleton to get a new Prototype instance.

Mark
 
Senthil S Kumar
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think the term "Singleton" is used very loosely here. The fact that you need a new Account object for every user makes it anything but "Singleton". Look into the "Session" or "Request" scope. Session scope will maintain one Account object for the entire HTTP Session and Request scope will create a new Account object for every request.
 
Mark Spritzler
ranger
Sheriff
Posts: 17278
6
IntelliJ IDE Mac Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I agree. Session scope sounds like what the user really wants. SIngleton is if you want just one instance for the container for all users.

Mark
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic