Getting Spring Application Context

Joe Skora picture Joe Skora · Sep 24, 2008 · Viewed 350.4k times · Source

Is there a way to statically/globally request a copy of the ApplicationContext in a Spring application?

Assuming the main class starts up and initializes the application context, does it need to pass that down through the call stack to any classes that need it, or is there a way for a class to ask for the previously created context? (Which I assume has to be a singleton?)

Answer

Don Kirkby picture Don Kirkby · Sep 24, 2008

If the object that needs access to the container is a bean in the container, just implement the BeanFactoryAware or ApplicationContextAware interfaces.

If an object outside the container needs access to the container, I've used a standard GoF singleton pattern for the spring container. That way, you only have one singleton in your application, the rest are all singleton beans in the container.