Search code examples
javaosgiequinox

What is a good way to structure a library which should work in OSGI- and non-OSGI environments?


I am writing an application which runs in an OSGI environment. Now I want to extract some code and put it in separate bundle/jar file to reuse it also in other applications (both, OSGI or non-OSGI).

My goal is to remove any dependencies to the OSGI environment classes, because it should also run in other apps which do not have all the jars of the various OSGI frameworks (e.g. Equinox). But at the same time I would like to register an OSGI Service in the OSGI environment if the Application is an OSGI app.

I have already separated the code and the only remaining piece of OSGI-dependent code is currently my Activator class which registers some class as an OSGI Service:

context.registerService(MyServiceInterface.class.getName(), new MyServiceImpl(), new Hashtable());

To remove the dependency, I think about the following:

  • I remove the Activator and OSGI dependencies from my bundle1
  • I create another bundle2 where I move the Activator

In the end I have my bundle1.jar which only has a Manifest.mf file to make it OSGI-ready, but there is no code anymore depending on OSGI framework classes. I have another bundle which only belongs to my current application which imports bundle1.jar and has the only purpose of registering the MyService.class on the OSGI container using an activator.

  1. Is this approach ok or are there any other best practices?
  2. Is registering a service in the OSGI environment good practice or is this something which always the host application should be responsible for?

Solution

  • Why not just leave the activator class in your bundle. When run in a non-OSGi environment, the activator class will not be called. When run in an OSGi environment, it will. Isolating you OSGi dependencies to the activator is a fine strategy.