开发者

How does Spring maintain singletons,prototypes... under the hood?

开发者 https://www.devze.com 2022-12-09 01:08 出处:网络
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

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 开发者_Go百科is the most often used and also speak to the thread-safety issues for service layer classes that may contain state but are singletons


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:

  1. 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.
  2. Prototype beans are not pre-instantiated; every time you ask for a prototype bean Spring creates and initializes a new instance.
  3. 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.
0

精彩评论

暂无评论...
验证码 换一张
取 消