Search code examples
osgiaemosgi-bundlesling

Filtering OSGi services using SlingScriptHelper#getService() method


I want to instantiate a service object in my jsp using sling taglib. In normal scenario where the service class is being implemented by only 1 class, its pretty simple:-

RegistrationService registrationService = sling.getService(RegistrationService.class);

But if the service class has more than 1 implementation classes, then how can we make sure to instantiate object for a particular class.

My java class are like:-
1. Interface: RegistrationService
2. Implementation Class 1:-

@Properties({@Property(name = "datasource", value = "SBWS"})
   @Service
   public class RegistrationServiceImpl implements RegistrationService{
   }


3. Implementation Class 2:-

@Properties({@Property(name = "datasource", value = "SOLR"})
   @Service
   public class RegistrationServiceImpl implements RegistrationService{
   }

How can I make sure that using

RegistrationService registrationService = sling.getService(RegistrationService.class);

in jsp will instantiate service for let say implementation class 1


Solution

  • Use SlingScriptHelper#getServices(...) method, which allows to specify a filter:

    RegistrationService[] services = sling.getServices(RegistrationService.class, "(datasource=SBWS)");
    if (services.length > 0) {
        // services[0] contains your service
    }
    

    Getting OSGi service and filtering it via properties is quite low-level stuff, consider moving it from JSP to a Java class.