Jan 30th, 2006, 09:34 AM
Singleton and Prototype Caching
I understand that spring caches singleton objects, but if I have a singleton object that has a dependency on a prototype, how do I get spring to inject the prototype into the singleton each time it brings back the cached instance of it. I thought this is what the BeanPostProcesses were doing?
Jan 30th, 2006, 10:00 AM
I haven't looked too deeply into the depths of this, so I might be completely wrong.
Originally Posted by punnooser
If beanA is marked as a singleton and beanB is a prototype, then everytime you ask Spring for beanA, it will return the same instance. Asking for beanB on the other hand will give you a new instance.
When Spring resolves dependencies, I expect it honours this, so if you have beanC (as well as beanA) which depend on beanB then they will each get a new instance of beanB (the prototype) *but* that instance will never change, i.e. beanA.getBeanB() will *always* return the same instance.
This is because beanA is a singleton and is only ever wired up once.
Jan 30th, 2006, 10:12 AM
You can have a look at the Target sources, especially the Prototype target source.
Jan 30th, 2006, 10:45 AM
Take a look at Lookup method injection in the reference manual. That will allow your singleton to always return a new reference to your prototype object each call.
Jan 30th, 2006, 11:37 AM
Of course; there is always the option to mark the original bean as a non-singleton.
You need to be careful with threading issues when using combined singletons/prototypes....
Jan 31st, 2006, 01:52 AM
To be honest, in most cases I don`t like the fact that something is done with a class if the class was not designed for it. If a class needs a new reference everytime, I make it expliciet by using some kind of factory. Now you can see what is going on. I can imagine there are cases you need to, but I don`t recommend making a habit from it.
Last edited by Alarmnummer; Jan 31st, 2006 at 02:14 AM.
Jan 31st, 2006, 04:14 AM
+1 from me.
Knowing whether a class is singleton or not allows you to make assumptions about it's behaviour (caching, thread safety etc.) As soon as "part" of the class is no longer singleton; bad things may happen.
As Alarmnummer says, the explicitness in this case would be very important IMHO.