注册服务并寻找服务

2024-04-02

我是 OSGI 新手,我想了解如何注册服务?总是通过吗BundleContext对象在Activator?有没有其他可用的方法?

假设我有一个界面IService并且有两个实现ServiceImpl1 and ServiceImpl2在同一个包中,我将它们注册如下。

context.registerService(IService.class.getName(), new ServiceImpl1(), props);
context.registerService(IService.class.getName(), new ServiceImpl2(), props);

但令人困惑的是我如何具体要求特定的服务实现?

serviceImplObject = (IService) dictionaryServiceTracker.getService();</pre>

我不确定在这种情况下我会得到哪种实现。另外,我没有看到任何选项来设置我需要什么类型的服务实现?


有多种方法可以以声明方式注册和使用服务。您可以使用声明式服务 (DS) http://wiki.osgi.org/wiki/Declarative_Services or 蓝图服务 http://www.ibm.com/developerworks/opensource/library/os-osgiblueprint/。还有其他的,但这些是实际规范的一部分。

至于您目前使用的程序化方法。注册时必须使用属性,创建跟踪器时必须使用过滤器。

Map<String, String. prop1 = new HashMap<String, String>();
prop1.put("name", "primary");
context.registerService(IService.class.getName(), new ServiceImpl1(), prop1);

Map<String, String. prop2 = new HashMap<String, String>();
prop1.put("name", "secondary");
context.registerService(IService.class.getName(), new ServiceImpl2(), props);

现在进行查找。

ServiceTracker primaryTracker = new ServiceTracker(bundleContext, "(&(objectClass=my.service.Service)(name=primary))", null);
ServiceTracker secondaryTracker = new ServiceTracker(bundleContext, "(&(objectClass=my.service.Service)(name=secondary))", null);

(更新了排名 - 感谢尼尔)如果没有过滤器,您将根据排名和服务 ID 获取服务。如果您在动态环境中运行(这些服务正在停止并重新启动),那么每次查找服务时都可能获得不同的实现。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

注册服务并寻找服务 的相关文章

随机推荐