我是OSGi的新手,尝试使用OSGi开发应用程序。我有一个OSGi服务,它有一个接口和两个实现。
接口:ExportService
实现:ExcelExportServiceImpl,PdfExportServiceImpl
ExportService是我的接口和ExcelExportServiceImpl,PdfExportServiceImpl是ExportService的实施方式。 我想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();
}
谢谢基督徒,工作! – SDJ