May 13th, 2010, 06:49 AM
When to set scope as prototype?
I am new to Spring. I was looking at bean scope attribute and saw that the default value is Singleton.
I looked at one of the application at my organization and at no place did I see any mention of scope "Prototype". In this case, none of the domain model objects were getting created using Spring, and there was no threading issue with the objects that were created using bean factory.
It looked to me like a static methods would have done the job wherever objects were specified as singletons.
So, when do I select the bean scope to be prototype?
If the default is Singleton, looks like Spring suggests and encourages to create only one instance as long as possible (except say for threading issues, persistence objects ...). Isn't this same as having static methods (Here I am overlooking the fact that bean in singleton scope is single within one bean factory's scope only, whereas static methods will be shared across classloader)?
May 13th, 2010, 08:22 AM
A singleton is something else as the ugly singleton pattern. The latter is quite impossible/hard to test (you cannot easily switch the implementation for instance, objects that need the instance need to now how to create/obtain it etc.).
May 13th, 2010, 09:51 AM
Thanks Marten. I had became aware of the java vs Spring notion of singletons while looking at this -->
Now, my query here is, why shouldn't we chose to use scope Prototype more often (and maybe set that as default).
By setting scope to singleton, you've always be alert so as not to use any instance variables on these bean defs. Also, somehow it doesn't feel very OO to me.
So, how often do you set the scope to prototype and what guides you on selecting the scope here (other than for threading issues and domain objects)?
May 13th, 2010, 09:57 AM
In general I never use prototype, I sometimes use it if you use a bean as a blueprint/template to create instances when I do a getBean on the BeanFactory/ApplicationContext
Services and repositories should be stateless by design, if they hold state they are wrong by design (imho). And why isn't it very OO?! You inject dependencies, have loose coupling (due to IoC). The fact that you don't use new to construct a new instance has nothing to do with OO ness...
May 17th, 2010, 06:52 AM
Sorry for late reply. When I started with Spring, I was assuming Spring IoC to be a factory primarily; now it feels more of a wiring solution.
I agree with your comment on State-less-ness of control classes, but again this criterion stems much from web-app centric development than the class classification itself.
May 17th, 2010, 06:55 AM
Tags for this Thread