Tuesday, December 1, 2009

Get ApplicationContext from everywhere

Create a static ApplicationContextProvider class to hold the ApplicationContext:

package com.abc;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

public class ApplicationContextProvider implements ApplicationContextAware {
private static ApplicationContext applicationContext = null;

public static ApplicationContext getApplicationContext() {
return applicationContext;
}
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
// Assign the ApplicationContext into a static variable
this.applicationContext = applicationContext;
}
}

Initialize the new bean in applicationContext.xml:
<bean id=”applicationContextProvider” class=”com.abc.ApplicationContextProvider”></bean”>

Get applicationContext:

ApplicationContext ctx = ApplicationContextProvider.getApplicationContext();
this.setDispatchManager((DispatchManager)ctx.getBean("dispatchManager"));

No comments: