Friday, October 23, 2009

Ways to get Spring ApplicationContext -In Spring DM

Couple of other ways to get hold of ApplicationContext (rather than doing new ClasspathXmlApplicationContext()).

1. Create a bean which is ApplicationContextAware

MessageChannel msgCh = (MessageChannel)ApplicationContextHolder.getApplicationContext().getBean("eventChannel");


public class ApplicationContextHolder implements ApplicationContextAware {

private static ApplicationContext appContext;

public void setApplicationContext(ApplicationContext ctx)

throws BeansException {

System.out.println("*** ApplicationContextHolder::setApplicationContext()...");

ApplicationContextHolder.appContext = ctx;


public static ApplicationContext getApplicationContext() {

return appContext;



This one is in the case of Spring DM

2. Accessing the ApplicationContext from BundleContext (By default every bundle publishes the Application Context as a Service).

public static ApplicationContext getApplicationContext() {

if (appCtx == null) {

try {

ServiceReference[] svcRef = bundleContext.getAllServiceReferences("org.springframework.context.ApplicationContext", "("); // Service name is the Bundle Symbolic Name

ServiceReference ref = svcRef[0];

appCtx = (ApplicationContext) bundleContext.getService(ref);

} catch (Exception e) {




return appCtx;


This is the preferred approach if you wish to use the Application Context from another bundle.

No comments:

Free Domain Names @!