@Scope("prototype") bean scope not creating new bean
Scope prototype means that every time you ask spring (getBean or dependency injection) for an instance it will create a new instance and give a reference to that.
In your example a new instance of LoginAction is created and injected into your HomeController . If you have another controller into which you inject LoginAction you will get a different instance.
If you want a different instance for each call - then you need to call getBean each time - injecting into a singleton bean will not achieve that.
Since Spring 2.5 there's a very easy (and elegant) way to achieve that.
You can just change the params proxyMode
and value
of the @Scope
annotation.
With this trick you can avoid to write extra code or to inject the ApplicationContext every time that you need a prototype inside a singleton bean.
Example:
@Service
@Scope(value="prototype", proxyMode=ScopedProxyMode.TARGET_CLASS)
public class LoginAction {}
With the config above LoginAction
(inside HomeController
) is always a prototype even though the controller is a singleton.
Just because the bean injected into the controller is prototype-scoped doesn't mean the controller is!