开发者

Spring injection and object instantiation

开发者 https://www.devze.com 2023-02-24 17:48 出处:网络
I am trying to better understand Spring instantiation of beans. To illustrate my doubts, let\'s assume we have a Service class being wired in a Controller, here are the questions:

I am trying to better understand Spring instantiation of beans. To illustrate my doubts, let's assume we have a Service class being wired in a Controller, here are the questions:

  1. How will Spring manage the lifecycle of the Controller? Will a new object be created per request?
  2. Once a Service is instantiaded and wired to a Controller, will Spr开发者_StackOverflow中文版ing re-use that object reference to wire it in to other beans?


  1. Like Servlets, Controllers' lifecycle spans beyond requests. All of controllers in the application are instantiated only once when application is started; afterwards those objects are re-used to service all requests.
  2. As Bozho pointed out, by default all beans are in singleton scope, therefore they will be re-used everywhere, unless specified otherwise.


The default scope is singleton, which means beans will be re-used (i.e. 1) no, a new object will not be created per request, and 2) yes, the object reference will be reused).

This can all be configured. Have a look at http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/beans.html#beans-factory-scopes.


It all depends on the bean scope. By default all beans are in singleton scope - that is, they are instantiated by the container only once.

If you specify @Scope("request") (or the xml equivalent) then the same service object (singleton) will be injected in all instances of the request-scoped controller. (But you rarely need request-scoped controllers)

0

精彩评论

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