I'm new to Virgo and OSGi. I have an existing Servlet application that runs on Tomcat. I want to move this application to VTS and let it have access to OSGi based services that I've created.
What is the recommended approach for a Web app to gain references to services? I have little to no experience with Spring, and we are looking to stay as close to OSGi standards as possible to allow us to run in different servers.
You could implement a BundleActivator to get access to a bundle context and get a reference to an OSGi service with it (or better use a ServiceTracker. Don't forget to declare the activator in the manifest file.
public class Activator implements BundleActivator {
private ServiceTracker<IStateServiceClient, IStateServiceClient> stateServiceTracker;
private static Activator instance;
/**
* Returns the shared instance
*
* @return the shared instance
*/
public static Activator getInstance() {
return instance;
}
@Override
public void start(BundleContext context) throws Exception {
instance = this;
stateServiceTracker = new ServiceTracker<IStateServiceClient, IStateServiceClient>(context,
IStateServiceClient.class.getName(), null);
stateServiceTracker.open();
}
@Override
public void stop(BundleContext context) throws Exception {
stateServiceTracker.close();
instance = null;
}
public IStateServiceClient getStateService() {
return stateServiceTracker.getService();
}
}
Manifest addition:
Bundle-Activator: my.package.Activator
In your web classes you can get access to the service like this:
Activator.getInstance().getStateService();
Remember to check for a null return value. If there is no active service registered in the OSGi environment atm then null will be returned.