Thursday, April 29, 2010

Handling Spring ApplicationContext events in Spring DM based OSGi environment

Listening for and handling Spring ApplicationContext events in a Spring DM setup needs needs two steps:

1) Implement a class for the interface org.springframework.osgi.context.event.OsgiBundleApplicationContextListener
import org.osgi.framework.Bundle;
import org.springframework.context.ApplicationContext;
import org.springframework.osgi.context.event.OsgiBundleApplicationContextEvent;
import org.springframework.osgi.context.event.OsgiBundleApplicationContextListener;
import org.springframework.osgi.context.event.OsgiBundleContextClosedEvent;
import org.springframework.osgi.context.event.OsgiBundleContextRefreshedEvent;

public class BundleApplicationContextTracker implements OsgiBundleApplicationContextListener {
public void onOsgiApplicationEvent(OsgiBundleApplicationContextEvent event) {
if(event instanceof OsgiBundleContextRefreshedEvent) {
// handle bundle start
} else if(event instanceof OsgiBundleContextClosedEvent) {
// handle bundle close
}
}
}

2) Expose the above class as an OSGi service by putting the following entries in Spring beans-config.xml

<beans:bean id="bundleContextTracker" class="org.mypackage.BundleApplicationContextTracker" scope="singleton"/>
<osgi:service id="bundleContextTrackerOSGi" ref="bundleContextTracker" interface="org.springframework.osgi.context.event.OsgiBundleApplicationContextListener"/>

No comments:

Post a Comment