Dynamically select service implementation at runtime using @Reference annotation?

I have an osgi implementation package containing an @Component that receives an @Reference to implement a service.

There are several packages that implement the service in different ways. No problem osgi picks one (using a rating or something similar). The problem is that the developer (I) is deciding which service implementation to use.

But is it possible to somehow indicate at runtime (when the bundles start or at a different time) which service implementation should the @Reference annotation choose?

I suspect I can use ServiceTracker to do this.

[edit] right after I posted I found a StackOverflow question (strategy pattern) that looks promising, the only thing I don't know is what kind of OperatorProvider services are available. I can implement a "selector service" and implement a ServiceTracker to manage the OperatorProvider services.

[edit2] Another way seems to be on this StackOverflow question with ConfigurationAdmin, you seem to be able to change "myService.target". Extending or implementing this specific ConfigurationAdmin functionality should do the job.

What's the preferred way to go or are there maybe better options?

+3


source to share


1 answer


There is a simple solution you can try. Each DS component can be connected to the config admin pid. Using this configuration, you can override the service filter for @Reference.

If you have, for example, @Reference myService;

you can set the config property "myService.target = (color = blue).



This would then limit the link to the service with the service property color=blue

.

+4


source







All Articles