首页 文章

多个OSGi服务

提问于
浏览
1

我是OSGi的新手,并尝试使用OSGi开发应用程序 . 我有一个OSGi服务,它有一个接口和两个实现 .
Interface: ExportService
Implementations: 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中实现两个不同的服务?

Update: Solution:
我在服务包的激活器中更改了以下代码,

@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();
}

1 回答

  • 4

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

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

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

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

相关问题