I've been using Spring for a while now but I really don't know how when I ask Spring to inject a DAO in multiple different service class that it is always the same class or if I require prototype is a new one every time and so on for session scope etc. Can anyone share some light on such especially 'Singletons' as it is the most often used and also speak to the thread-safety issues for service layer classes that may contain state but are singletons
+2
A:
I'm not trying to be a "LMGTFY" jackass here, but I doubt anyone will explain it better than Spring documentation on bean scopes.
As a quick rehash, though, to address your specific questions:
- Singleton beans (which is the default scope) are normally pre-instantiated (unless configured otherwise) by bean factory when it's loaded. Think of it as Map of bean by its id. When you ask for a bean (directly or as dependency for other bean or when it's autowired) it's obtained from that map.
- Prototype beans are not pre-instantiated; every time you ask for a prototype bean Spring creates and initializes a new instance.
- As far as multi-threading goes, Dean J (who's deleted his answer) is right - your services should not maintain a state or, if they do, should be synchronized appropriately.
ChssPly76
2009-10-14 17:49:41
LMAO!! you know i've never even seen this before and I've read this doc many times but only looking for what I want...should have kept to my original pattern but then SO came to mind lol...the SO Substitution Principle!
non sequitor
2009-10-14 18:13:43
@ChssPly76: Actually this already told me what I knew, I as looking for more like the internals, whether there's `Threadlocal` use, the `Map` with the bean ids where/how is this maintained etc
non sequitor
2009-10-17 21:53:25
There's no ThreadLocal and no synchronization, everything is contained within BeanFactory instance. For Spring MVC you can choose to have Spring synchronize your controller's methods on session but that's about it. You can take a look at (http://static.springsource.org/spring/docs/2.5.x/api/org/springframework/beans/factory/support/AbstractBeanFactory.html) AbstractBeanFactory source (and its subclasses, like DefaultListableBeanFactory) if you're interested in how internals work.
ChssPly76
2009-10-17 22:05:27