我是 OSGi 的新手,正在尝试使用 OSGi 开发应用程序。我有一个 OSGi 服务,它有一个接口(interface)和两个实现。
接口(interface):ExportService
实现:ExcelExportServiceImpl
、PdfExportServiceImpl
ExportService
是我的接口(interface),ExcelExportServiceImpl
、PdfExportServiceImpl
是 ExportService
的实现。
我想要 ExcelExportServiceImpl
和 PdfExportServiceImpl
作为两个不同的服务。
从我的应用程序包中,如果我想使用 excel 导出,我应该能够在不涉及 PdfExportServiceImpl
的情况下调用 ExcelExportServiceImpl
服务。
如何注册两个具有相同接口(interface)的不同服务?
@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()
作为类名。如何通过一个接口(interface)在同一个 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();
}
最佳答案
上面的代码将注册两个具有相同接口(interface)的不同服务。这是正确的。
问题在于,通过接口(interface)绑定(bind)服务的消费者将获得这些服务之一,但无法决定哪个是正确的。
解决此问题的一种方法是为每个服务注册添加属性。例如,您可以在 pdf 上设置一个 proerty type=pdf。
然后客户端可以通过接口(interface)和类似 (type=pdf) 的 ldap 过滤器绑定(bind)服务。然后它将只匹配 pdf ExportService 服务。
关于java - 多个 OSGi 服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36861785/