2016-04-26 138 views
1

我是OSGi的新手,尝试使用OSGi开发应用程序。我有一个OSGi服务,它有一个接口和两个实现。
接口:ExportService
实现:ExcelExportServiceImpl,PdfExportServiceImpl
ExportService是我的接口和ExcelExportServiceImpl,PdfExportServiceImplExportService的实施方式。 我想ExcelExportServiceImpl和PdfExportServiceImpl作为两种不同的服务。
从我的应用程序包中,如果我想使用Excel导出,我应该能够调用ExcelExportServiceImpl服务而不涉及PdfExportServiceImpl。如何注册两个具有相同接口的不同服务?多个OSGi服务

@Override 
public void start(BundleContext context) throws Exception { 
     context.registerService(ExportService.class.getName(), new ExcelExportServiceImpl(), null); 
     context.registerService(ExportService.class.getName(), new PdfExportServiceImpl(), null); 
    } 
} 

就目前来看,我想出了在我激活了上面的代码,它似乎并没有工作,因为这两种服务有ExportService.class.getName()作为类名。如何通过一个接口在同一捆绑中实现两种不同的服务?

更新:
解决方案:

我在服务bundle的激活改变了代码如下,

@Override 
public void start(BundleContext context) throws Exception { 
     Hashtable excelProperty = new Hashtable(); 
     excelProperty.put("type", "excel"); 
     excelServiceRegistration = context.registerService(ExportService.class.getName(), new ExcelExportServiceImpl(), excelProperty); 
     Hashtable pdfProperty = new Hashtable(); 
     pdfProperty.put("type", "pdf"); 
     pdfServiceRegistration = context.registerService(ExportService.class.getName(), new PdfExportServiceImpl(), pdfProperty); 
} 

而在我的应用程序包,我添加了以下过滤器

public static void startBundle(BundleContext context) throws InvalidSyntaxException { 
    String EXCEL_FILTER_STRING = "(&(" + Constants.OBJECTCLASS + "=com.stpl.excel.api.ExportService)" + "(type=excel))"; 
    String PDF_FILTER_STRING = "(&(" + Constants.OBJECTCLASS + "=com.stpl.excel.api.ExportService)" + "(type=pdf))"; 
    Filter excelFilter = context.createFilter(EXCEL_FILTER_STRING); 
    Filter pdfFilter = context.createFilter(PDF_FILTER_STRING); 
    ServiceTracker excelService = new ServiceTracker(context, excelFilter, null); 
    ServiceTracker pdfService = new ServiceTracker(context, pdfFilter, null); 
    excelService.open(); 
    pdfService.open(); 
} 

回答

4

上面的代码将使用相同的接口注册两个不同的服务。这是对的。

问题是,通过接口绑定服务的使用者将获得这些服务之一,并且无法确定哪个服务是正确的。

解决此问题的一种方法是为每个服务注册添加属性。例如,你可以在pdf上设置proerty type = pdf。

然后,客户端可以通过接口和ldap过滤器(type = pdf)绑定服务。它将只匹配pdf ExportService服务。

+0

谢谢基督徒,工作! – SDJ