I'm sure this has been asked a hundred times before but I can't seem to find the question so feel free to refer me to other stackoverflow answers.
What do most Spring users do for objects that are non-singleton beans that require injection? For example, I have classes like Customer where I want to instantiate a new one each time. Lets say it is an entity and I want to inject listeners to iterate through in @PreRemove or somewhere else. The usual solution is to use @Configurable but that almost seems a workaround and I was wonder if there was a more canonical way to handle these.
The only thing I can think of is to create a factory newCustomer instance method in my CustomerRepository class which IS a managed bean. Then instead of injecting listeners into Customer (the most natural place) I inject them into the CustomerRepository and specify them as an explicit constructor argument to Customer ala new Customer( injectedListeners ).
Do people tend to just use Configurable or is there a better way to inject non-singleton instances? Or do most users create a factory method as above? The entity example is just an example, I have other objects that are non-singleton, are typically new'd but require injection.
Would this be handled differently in something like Guice? How would you do it just using JSR-330 features?
You can make beans non-singletons if you like. Depends on whether you are ok with the XML:
Which will give you a new instance every time. Each instance will be initialized with injected values.
You can use this annotation too: