Jerry Jacob's Blog

Making your Spring application, ‘Context Aware’

Posted in Java/ J2EE by Jerry Jacob on July 20, 2009

Suppose you have some java classes which are unable (or you don’t want it) to be wired to the Spring application context; for example, an auto generated web service client class! But you do want to use the dependency injection feature of Spring to get some of the other beans injected in to this class. How can we make this happen? One way to achieve this would be to use the ApplicationContextAware interface provided by Spring.

Create a class named ApplicationContext which implements  ApplicationContextAware. The inherited method, ‘setApplicationContext(…)’ will get called during the creation of this bean, providing the reference to the context. Our program should store this for a later interaction with the context.

package jerry.jacob;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
public class ApplicationContextProvider implements ApplicationContextAware {
    private static ApplicationContext ctx = null;
    public static ApplicationContext getApplicationContext() {         
        return ctx;    
    public void setApplicationContext(ApplicationContext ctx) throws BeansException {
        // Assign the ApplicationContext into a static method
        this.ctx = ctx;

Initialize the new bean in applicationContext.xml

<bean id="applicationContextProvider" class="jerry.jacob.ApplicationContextProvider"></bean>

Now you can call the static method, getApplicationContext(), from any class in your application, to get assess to the Spring ApplicationContext.