Pivotal Knowledge Base

Follow

Getting a Reference to the ApplicationContext in a Spring Application

Environment

 Product  Version
 Spring  All

Purpose

This article provides a way to get the reference to the ApplicationContext in a Spring application.

Resolution

To get a reference to the ApplicationContext in a Spring application, it can easily be achieved by implementing the ApplicationContextAware interface. Spring will automatically detect this interface and inject a reference to the ApplicationContext: view rawMyBeanImpl.java hosted by GitHub.

package foo;
 
import org.springframework.context.ApplicationContextAware;
 
public class MyBeanImpl implements ApplicationContextAware {
     private ApplicationContext ctx;
 
     public void setApplicationContext(ApplicationContext context) {
this.ctx=context;
     }
}

Another option is to use @Autowired or @Inject annotations in case of Annotation-based container configuration:

package foo;
 
import org.springframework.beans.factory.annotation.Autowired;
 
public class MyBeanImpl {
     @Autowired
     private ApplicationContext ctx;
}

Additional Information

View rawMyBeanImpl.java hosted by GitHub for further details. 

Comments

Powered by Zendesk