Search code examples
javaosgiapache-felix

OSGi service class dependencies


I was wondering what would be a good way of organising my bundles so that classes required as parameters to services can be shared between them.

I have a couple of services interfaces which expose class types which will need to be referenced between bundes e.g.:

public interface DoesThis {
   public CustomClassB doSomething(CustomClassA customClassA);
}

From my understanding CustomClassA (if defined in the same bundle as the exposed service) would not be available to other bundles so would it be best to expose classes references between bundles in a package which is then exported?

Just as a sub question: Are services and package exports supposed to work hand-in-hand... It wasn't clear from the documentation I was reading if this was the case?

Thanks


Solution

  • Basically, yes. All types referenced by the interface must be in an exported package. There are a few options:

    • They could be in the same package as the interface, in which case they will naturally be exported at the same time as the interface, because in OSGi we always export/import whole packages.
    • They could be in a different package but exported by the same bundle as the service interface.
    • They could be in a different package and exported by a different bundle. In this case the service interface bundle must import that package.

    If you think about it, it doesn't make sense for the types not to be exported. For example, how could a consumer call your doSomething method if it cannot create an object of type CustomClassA to pass in, or if it cannot understand the return type CustomClassB?

    Regarding your sub question... yes, package exports exist principally to support the service registry. Services can only work if the provider and the consumer can come to an agreement on the "contract" of the service, which in Java terms means they load the same interface.