使用SlingScriptHelper#getService()方法过滤OSGi服务

par*_*682 2 osgi sling osgi-bundle aem

我想使用sling taglib在我的jsp中实例化一个服务对象.在正常情况下,服务类只由一个类实现,它非常简单: -

RegistrationService registrationService = sling.getService(RegistrationService.class);
Run Code Online (Sandbox Code Playgroud)

但是如果服务类有多个实现类,那么我们如何确保为特定类实例化对象.

我的java类是这样的: -
1.接口:RegistrationService
2.实现类1: -

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


3.实施类2: -

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

我怎样才能确保使用

RegistrationService registrationService = sling.getService(RegistrationService.class);
Run Code Online (Sandbox Code Playgroud)

在jsp中将实例化服务,让我们说实现类1

Tom*_*wek 5

使用SlingScriptHelper#getServices(...)方法,允许指定过滤器:

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

获取OSGi服务并通过属性过滤它是非常低级的东西,考虑将它从JSP转移到Java类.