【发布时间】:2013-12-29 21:26:39
【问题描述】:
我刚刚开始亲身体验 OSGI 技术,但基本的查询很少。 这是我所做的:
在名为“com.mypackage.osgi.bundle.service”的包中创建了一个 HelloWorld 接口。这个接口公开了一个方法:public String sayHello(String arg);
在名为“com.mypackage.osgi.bundle.service.impl”的包中创建了一个 HelloWorldImpl 类。该类实现了 HelloWorld 接口,并提供了 sayHello() 方法的实现。
在名为“com.mypackage.osgi.bundle.activator”的包中创建了一个 HelloWorldActivator 类。该类实现了BundleActivator接口,实现了接口的start()和stop()方法。
在 start() 方法中,我通过“BundleContext”将此捆绑包注册为服务。代码如下:
公共类 HelloWorldActivator 实现 BundleActivator {
ServiceRegistration helloServiceRegistration; public void start(BundleContext context) throws Exception { HelloWorld helloService = new HelloWorldImpl(); helloServiceRegistration =context.registerService(HelloWorld.class.getName(), helloService, null); System.out.println("Service registered"); } public void stop(BundleContext context) throws Exception { helloServiceRegistration.unregister(); System.out.println("Service un-registered"); } }
然后,我使用 maven 插件将此项目打包为 OSGI 包,并将其部署在 OSGI 容器 (Equinox) 上。在说明中,我将接口公开为导出包。我可以看到我的 OSGI 包已成功部署为 OSGI 容器上的服务(包 id 显示为 ACTIVE 状态,并且我可以在 osgi 控制台上看到“服务注册”输出)。
现在我的下一步是将上述 OSGI 捆绑包作为服务使用。 我知道为了做到这一点,我可以使用“ServiceReference”。
假设我现在正在创建一个完全新的 java 项目(因此该项目的工作区中没有与上面创建的工作区的链接),这样它将充当上面创建的服务的消费者.
我的查询是 - 我需要在这个新的 java 项目中创建 HelloWorld 接口的“副本”吗?换句话说,我需要在这个新项目的工作区中将此接口作为“存根”吗?
我问这个的原因是,如果我在新项目的工作区中没有“HelloWorld”接口的副本,我将在下面提到的第 2 行和第 3 行出现编译错误。
公共类 ConsumerActivator 实现 BundleActivator {
ServiceReference helloServiceReference; public void start(BundleContext context) throws Exception { helloServiceReference= context.getServiceReference(HelloWorld.class.getName()); //2 HelloWorld helloService =(HelloWorld)context.getService(helloServiceReference); //3 System.out.println(helloService.sayHello("Test user")); } public void stop(BundleContext context) throws Exception { context.ungetService(helloServiceReference); } }
那么,说消费者捆绑包应该有它打算使用的服务接口的“存根”是否正确?
很抱歉,这听起来是一个非常基本的问题,但我需要澄清一下,因为我在网上的任何地方都找不到任何提及它的内容。提供的所有示例都假定消费者和服务都是同一代码工作区的一部分。
非常感谢提前澄清。
最好的问候 磅
【问题讨论】:
标签: service osgi bundle stub consumer