Friday, April 21, 2006

Sharing Instances in Spring

So I had a fairly basic problem that I probably have solved before but wasn't able to remember and took some time to work out.

I had three objects A, B and C. Both B and C need to share the same instance of A. But I want to create multiple Bs and Cs – so they are not singletons. I also did not want other Bs and Cs to share the one instance of A so making A a singleton was also out of the question.

There’s several ways I came up with but none of which I was particularly happy with:
1/ Flatten out the dependencies – make C depend on B which depends on A for instance.
2/ Make A a singleton and create bunches Bs and Cs by using multiple BeanFactories.
3/ I could throw away dependency injection and let the objects using B and C construct/set-up B and C using A.

The solution that I finally settled on is creating a BCFactory (interface) that requires A, constructs B and C (in the implementation) and has getB() and getC() methods.
Post a Comment