注册服务并寻找服务 [英] Registering a service and looking for the service

查看:72
本文介绍了注册服务并寻找服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是OSGI的新手,我想了解如何注册服务?是否总是通过Activator中的BundleContext对象?是否有其他替代方法?

I am new to OSGI, I am trying to understand how to register a service? is it always through BundleContext object in Activator? Is there any alternate way available?

假设我有一个接口IService,并且在同一个捆绑软件中有两个实现ServiceImpl1ServiceImpl2,如下所示.

Let say I have a Interface IService and there are two implementation ServiceImpl1 and ServiceImpl2 in same bundle I am registering them as below.

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

但是我要如何特别地要求特定的服务实现是一个困惑?

But confusion is how do I specifically ask for a particular service implementation?

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

我不确定在这种情况下我会得到哪种实现.我也看不到任何设置我需要哪种类型的服务实现的选项?

I am not sure which implementation i would get in this case. Also I don't see any option to set what type of service implementation i need?

推荐答案

有声明式注册和使用服务的替代方法.您可以使用声明性服务(DS)

There are alternatives for registering and consuming services declaratively. You can use either Declarative Services (DS) or Blueprint Services. There are others as well, but these are part of the actual specification.

关于您当前正在使用的程序化方法.注册时必须使用属性,创建跟踪器时必须使用过滤器.

As for the programatic approach you are currently using. You have to use the properties when you register and a filter when you create your tracker.

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获得该服务.如果您在动态环境中运行(这些服务正在停止并重新启动),则每次查找该服务时都有可能获得不同的实现.

(Updated with regards to ranking - thanks Neil) Without the filter, you will get the service based on its ranking and service ID. If you are running in a dynamic environment (where these services are stopping and restarting) then it possible to get different implementations each time the service is looked up.

这篇关于注册服务并寻找服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆