Wednesday, March 23, 2011

Spring OSGi - how to get ApplicationContext for a bundle

Using Spring DM, a Spring ApplicationContext is created for each Spring DM. The ApplicationContext is published as an OSGi service.

The following code can be used to lookup the ApplicationContext in OSGi service registry.


public static ApplicationContext getApplicationContext(final BundleContext bundleContext) {
        final String filter = "(org.springframework.context.service.name=" + bundleContext.getBundle().getSymbolicName() + ")";
        final ServiceReference[] applicationContextRefs;
        final ApplicationContext applicationContext;
       
        try {
            applicationContextRefs = bundleContext.getServiceReferences(ApplicationContext.class.getName(), filter);
        } catch (final InvalidSyntaxException e) {/>
            throw new RuntimeException(e);
        }
       
        if(applicationContextRefs.length != 1) {
            return null;
        }
       
        applicationContext = (ApplicationContext) bundleContext.getService(applicationContextRefs[0]);
       
        return applicationContext;
}


See Application Context Service Publication for details

No comments:

You should follow me
on twitter