多个OSGi服务

问题描述 投票:2回答:1

我是OSGi的新手,并尝试使用OSGi开发应用程序。我有一个OSGi服务,它有一个接口和两个实现。

界面:ExportService

实施:ExcelExportServiceImplPdfExportServiceImpl

ExportService是我的界面和ExcelExportServiceImplPdfExportServiceImplExportService的实现。

我想要ExcelExportServiceImplPdfExportServiceImpl作为两种不同的服务。

从我的应用程序包中,如果我想使用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
1个回答
4
投票

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

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

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

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

© www.soinside.com 2019 - 2024. All rights reserved.