【发布时间】:2016-04-26 10:08:44
【问题描述】:
我是 OSGi 的新手,正在尝试使用 OSGi 开发应用程序。我有一个 OSGi 服务,它有一个接口和两个实现。
接口:ExportService
实现:ExcelExportServiceImpl、PdfExportServiceImpl
ExportService 是我的接口,ExcelExportServiceImpl、PdfExportServiceImpl 是 ExportService 的实现。
我希望 ExcelExportServiceImpl 和 PdfExportServiceImpl 作为两个不同的服务。
从我的应用程序包中,如果我想使用 excel 导出,我应该能够调用ExcelExportServiceImpl 服务而不涉及PdfExportServiceImpl。
如何注册两个具有相同接口的不同服务?
@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();
}
【问题讨论】:
标签: java service osgi osgi-bundle