Recently I came across this requirement, where we have a Foo bean and a Bar bean; both are Singletons, and Bar needs to be injected into Foo.
However, Bar is a heavyweight bean for resource/memory, hence we need to delay its instantiation to the point where Foo actually calls a method on it. The catch is, Foo has to be eagerly instantiated. So what are different ways to do it?
I’ve shared my solution in an answer below. It will be great to learn of any other approaches.
In essence, this is what I did:
1) make
Barlazily instantiated,2) use a
LazyInitTargetSourceand point it to the bean above,3) use a `ProxyFactoryBean’ which points to the target source above,
4) make
Fooeagerly instantiated and inject the proxy above into it.This solution is more verbose and more complex than using
lookup-methodsolution. Howeverlookup-methodsolution is difficult to unit test and I feel that it couples more tightly with Spring compared to the other solution.Following is the confuguration: