Search code examples
javaosgiapache-felix

Dynamically select a service implementation at runtime using @Reference annotation?


I have an osgi implementation bundle containing an @Component which gets a @Reference to a service implementation.

There are multiple bundles which implement the service in different ways. No problem osgi picks one (using ranking or something similar). The problem is that the developer (I) make the decision about which service implementation to use.

But is it possible somehow specify at runtime (when the bundles start or at another time) which service implementation the @Reference annotation should select?

I suspect i can use ServiceTracker to do this.

[edit] just after i posted i found https://stackoverflow.com/a/5804265/7820234 (strategy pattern), which looks promising, the only thing is that i don't know which OperatorProvider services are available. I can implement the "selector service" and implement a ServiceTracker to manage the OperatorProvider services.

[edit2] Another way seems to be https://stackoverflow.com/a/32813211/7820234 with ConfigurationAdmin you seem to be able to change "myService.target". Extending or implementing this specific functionality of ConfigurationAdmin should do the job.

Which is the preferred way to go or are there maybe better options?


Solution

  • There is a simple solution you can try. Every DS component can be attached to a config admin pid. Using this config you can override the service filter for the @Reference.

    If you for example have @Reference myService; then you can set the config property "myService.target=(color=blue).

    This would then limit the reference to a service with the service property color=blue.