Spring get current ApplicationContext

If you're implementing a class that's not instantiated by Spring, like a JsonDeserializer you can use:

WebApplicationContext context = ContextLoader.getCurrentWebApplicationContext();
MyClass myBean = context.getBean(MyClass.class);

In case you need to access the context from within a HttpServlet which itself is not instantiated by Spring (and therefore neither @Autowire nor ApplicationContextAware will work)...

WebApplicationContext applicationContext = WebApplicationContextUtils.getWebApplicationContext(getServletContext());

or

SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this);

As for some of the other replies, think twice before you do this:

new ClassPathXmlApplicationContext("..."); // are you sure?

...as this does not give you the current context, rather it creates another instance of it for you. Which means 1) significant chunk of memory and 2) beans are not shared among these two application contexts.


Simply inject it..

@Autowired
private ApplicationContext appContext;

or implement this interface: ApplicationContextAware


I think this link demonstrates the best way to get application context anywhere, even in the non-bean class. I find it very useful. Hope its the same for you. The below is the abstract code of it

Create a new class ApplicationContextProvider.java

package com.java2novice.spring;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

public class ApplicationContextProvider implements ApplicationContextAware{

    private static ApplicationContext context;

    public static ApplicationContext getApplicationContext() {
        return context;
    }

    @Override
    public void setApplicationContext(ApplicationContext ac)
            throws BeansException {
        context = ac;
    }
}

Add an entry in application-context.xml

<bean id="applicationContextProvider"
                        class="com.java2novice.spring.ApplicationContextProvider"/>

In annotations case (instead of application-context.xml)

@Component
public class ApplicationContextProvider implements ApplicationContextAware{
...
}

Get the context like this

TestBean tb = ApplicationContextProvider.getApplicationContext().getBean("testBean", TestBean.class);

Cheers!!