views:

467

answers:

3

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 each 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?

A: 

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.

Brian Agnew
+1  A: 

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.

duffymo
so you saying POJO classes don't really worry about state, they are just passed around? But don't you create say a User object, then set its properties, then persist it. if its a singleton (default), won't setting the username effect all other instances going forward?
mrblah
No, if you create a User object and persist it, you called new to create it and save to put it into the database as part of a transaction. The User reference may or may not be GC'd when it goes out of scope. That's not under Spring's control. You don't configure that the way you do a service or DAO.
duffymo
ah ok, 24 hours later reading what you wrote makes sense. you don't setup POJO's with DI....
mrblah
+1  A: 

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.

Nathan Hughes