Tuesday, March 16, 2010

Access to ApplicationContext in Spring based Web applications

Recently in a Spring WS application , i had to get access to the Spring ApplicationContext and it turns out that it is not so well documented. Spring ApplicationContext can be created either by using
ClassPathXmlApplicationContext:
ClassPathXmlApplicationContext appContext = new ClassPathXmlApplicationContext(new String[] {"applicationContext.xml", "applicationContext-part2.xml"})

WebApplicationContext:

If we have access to the servletContext 

WebApplicationContext wac = WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext);

In a web/Spring WS app, if we do not have access to the servletContext and if we would to like use the existing ApplicationContext , the following approach might be the way to go:


Create a class ApplicationContextContainer that implements ApplicaionContextAware and have it be defined as a
bean in Spring context xml file.

import org.springframework.beans.BeansException;

import org.springframework.context.ApplicationContext;

import org.springframework.context.ApplicationContextAware;

public class ApplicationContextContainer implements ApplicationContextAware {

private ApplicationContext appContext; 


@Override 

public void setApplicationContext(ApplicationContext applicationContext)
throws BeansException {

 this.appContext = applicationContext; 

} 
 

public ApplicationContext getAppContext(){

 return appContext; 

} 

}
Create a bean definition for the above class in the spring context file

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



And by injecting the bean applicationContextProvider, the spring ApplicationContext is accessible in the rest of the application.