Access multiple implementation of an OSGi service from a Sling servlet dynamically
Use Case
Here we are going to showcase how we can access multiple implementations of an OSGI service dynamically (at run time) from a sling servlet.
Break the requirement
To deal with the requirement we are going to break it in multiple requirements –
- Creating multiple implementations of an OSGi service.
- Giving an unique meaningful identifier to the service which will be used to target a specific implementation.
- Creating a set of objects which will hold one instance object for each service implementation.
- Input and logic to Switch between the implementation.
Creating multiple implementations
We can create multiple implementations for a service by implementing our service interface, same way as we create a single implementation of a service.
Giving an unique meaningful identifier to the Service Implementations
To give an identifier to a service we can utilize @Properties annotation, and set a property name according to your project needs and value will be different for each implementation. Here we are using productType as property name and core is the value for default implementation.
Creating a Map of objects
Now that we have created multiple implementations and given some identifier, our next goal is to find the way of getting instance objects created inside the OSGi container and collect them as a Map (to allow fetching particular instance object using identifier).
This can be achieved very easily by utilizing bind and unbind methods which get executed when an object gets created or destroyed respectively. And we can associate a service interface for which we need to track object creation or modification.