我是 OSGI 的新手,我想了解如何注册服务?它总是通过 Activator
中的 BundleContext
对象吗?有没有其他可用的方法?
假设我有一个接口(interface) IService
并且在同一个包中有两个实现 ServiceImpl1
和 ServiceImpl2
我正在如下注册它们。
context.registerService(IService.class.getName(), new ServiceImpl1(), props);
context.registerService(IService.class.getName(), new ServiceImpl2(), props);
但令人困惑的是我如何专门要求特定的服务实现?
serviceImplObject = (IService) dictionaryServiceTracker.getService();</pre>
我不确定在这种情况下我会得到哪种实现。我也没有看到任何选项来设置我需要什么类型的服务实现?
最佳答案
有一些替代方法可以以声明方式注册和使用服务。您可以使用 Declarative Services (DS)或 Blueprint Services .还有其他的,但这些是实际规范的一部分。
至于您目前使用的程序化方法。您必须在注册时使用属性,在创建跟踪器时使用过滤器。
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);
(更新了排名 - 感谢 Neil) 如果没有过滤器,您将根据其排名和服务 ID 获得服务。如果您在动态环境中运行(这些服务正在停止和重新启动),则每次查找服务时都可能获得不同的实现。
关于java - 注册服务并寻找服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13974271/