views:

1660

answers:

1

I need to get the spring application context from a non bean object. In another thread in SO, the accepted answer suggests to use singleton to get the application context. Getting Spring Application Context

But using singleton makes my code more coupled and less testable, the usual problems discussed in many threads (e.g. What is so bad about Singletons )

The question, is there an elegant way to get the application context from a non bean object without using singleton?

+6  A: 

There's always the bootstrapping problem. For web applications there's usually the outer servlet filter that handles the situation.

If not a web-app, there's no way around some kind of outer singleton or bootstrapper. But; using a singleton here should only affect the testability of that single bootstrapper class. There should really only be very few places in your code that need to reference the container in any explicit manner. So it does not really increase coupling significantly.

Or to rephrase, there should really only be very few non-bean objects that need to access the spring container. If this is not the case, then you're probably not using spring optimally. And most/all of those that need the container should probably just implement BeanFactoryAware or ApplicationContextAware

krosenvold
+1 on this. Singletons should generally be avoided in your application code. For certain kinds of bootstrapping or infrastructure it's not a big deal. Odds are you will not need to unit test your bootstrapper anyways. :)
cliff.meyers