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:
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.
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.