我是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