Skip to content

How to get ApplicationContext instance

Sometimes, we want to get the ApplicationContext instance, there are several ways to achieve.

Using Bean Injection

We can inject the ApplicationContext as a bean into our bean.

Java
@Component
public class ExampleBean {
    @Autowired
    private ApplicationContext applicationContext;

    public ApplicationContext getApplicationContext() {
        return applicationContext;
    }
}

Or, uses @Inject annotation or constructor injection.

Using ApplicationContextAware

ApplicationContextAware is an interface that to be implemented by any object that wishes to be notified of the ApplicationContext that it runs in.

Java
@Component
public class ExampleBean implements ApplicationContextAware {
    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        ApplicationContextProvider.applicationContext = applicationContext;
    }

    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }
}