Spring Framework - Application Context - three ways to get to the application context
This article shows you three different ways how to get to the Spring Framework Application Context in your code.
Summary
(This is a repost of an older article I wrote in 2010). In searching Google for “Spring ApplicationContextAware ”, you will come across a lot of recommendations and I also see a lot of folks continuing to complain saying that their setApplicationContext method does not get invoked. So to help clarify, I’m blogging a few notes in hope that it helps clarify how the context works.
Method-1
In your class you implement ApplicationContextAware class like this:
Method-2
If you are in a Java Servlet, you can do the following:
So the question one would ask is when to use what? And the answer is. Depends on how you are invoking Spring.
What works for Method #1: when you invoke Spring you are using the DispatcherServlet link this. Then Method #1 will resolve the implementation of ApplicationContextAware and call the setApplicationContext() method to set the context.
If you are not using the DispatcherServlet and you are initializing Spring using a Listener and you have your own Servlet that’s driving the Request\Response scope then use Method #2. Below is an example of how the web.xml will look like in this case.
I hope this clarifies why sometimes even though you have implemented the ApplicationContextAware interface, your setter does not get invoked.
[09/12/2010] Here is a third way to get your context:
Create the following class with a static method to get your context:
and in your spring bean configuration xml file add the following:
And now in your classes, you can do the following:
If you find this article useful, consider signing up for my email or repost this on your favorite social site. See links on the right navigation.
To be innovative, we can't look to what others have done. The whole idea of blazing a path is that there was no path there before. Be innovative today!