I have a singleton Spring bean (and it has to stay a singleton) which needs a fresh instance of another bean (Lets call it X) every time a certain method executes.
So far I looked at the following approaches:
-
just create X using new. This worked for a while but now we need spring AOP features for X, so this doesn’t work anymore, since the resulting instances are not Spring managed.
-
I considered a FactoryBean as a dependency, but I would only get a single X instance from the FactoryBean, which doesn’t meet my first instance.
-
the current plan is to manually lookup X in the Spring context, and declare it there with a prototype dependency. This should work, but I think it is really ugly.
=> How can I inject a factory in my bean so that I can call its factory method any time I see fit and getting a spring managed instance out of it.
The means of choice for a scenario like this is called lookup method injection. In short, this uses the approach of a call to a bean method resulting in a new bean instance created. You’d start by creating a class with an abstract method that will eventually provide the dependency instance:
You now go ahead and configure a prototype bean definition for the dependency:
As well as the client using the
lookup-methodelement to always get a fresh instance of the dependency for each method call:This will cause a CGLib proxy being created for
MyClientand the method declaration ofgetDependencyInstance(…)being backed by aTargetSourcewith a reference to theBeanFactoryand the name of the bean to be looked up. On each method invocation the bean lookup will be triggered and a fresh instance of the prototype configured bean is returned.