开发者

spring wiring, singleton versus prototype

just reading up on spring, and when using DI in spring, if you set the bean to be a singleton (default), then a single instance of the class will be 'dispensed', while prototype forces a new instance ea开发者_Python百科ch time.

What are the ramifications of having the same instance dispensed by the container each time? does that mean there will be shared state?

i.e. if the instance is modified somewhere, all future object creations will actually be getting a 'dirty' object and not a 'new' one?


Since you're usually programming to an interface with Spring, the objects that are DI managed don't have state to worry about. There's no concern about "dirty" in that case. Repositories, services, controllers - all should have little or no state to speak of.


If you declare the scope of a Spring-managed bean as a singleton, yes, there will be shared state. Typically you don't use inappropriate instance variables the same way you would avoid that when making a servlet. But a controller's state would include the service it calls, the service's state would include references to the data access objects it uses.


The singleton object is just that. Each object that has a singleton injected gets a reference to the same object. Any changes in that object will be visible (via behaviour or otherwise) to all the consumers of that object.


Definitely you should avoid maintaining state in a singleton session bean unless you use some sort of synchronization. Ideally, singletons should not have instance fields. Use stateful beans when you need to maintain state in a conversational way. When you are done with a stateful bean, you have to explicitly remove it, otherwise you have memory leak on your hands.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜