Spring injection and object instantiation
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:
- How will Spring manage the lifecycle of the Controller? Will a new object be created per request?
- 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?
- 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.
- 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)
精彩评论