首页 文章

OSGI捆绑服务使用者是否需要创建服务接口的“存根”?

提问于
浏览
0

我刚刚接触了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”将此包注册为服务 . 代码如下所示:

public class HelloWorldActivator实现了BundleActivator {ServiceRegistration helloServiceRegistration;

public void start(BundleContext context)抛出Exception {

HelloWorld helloService = new HelloWorldImpl();
helloServiceRegistration = context.registerService(HelloWorld.class.getName(),helloService,null); System.out.println(“服务注册”); }

public void stop(BundleContext context)抛出Exception {

helloServiceRegistration.unregister(); System.out.println(“服务未注册”);
}}

然后我使用maven插件将此项目打包为OSGI包,并将其部署在OSGI容器(Equinox)上 . 在说明中,我将接口公开为export-package . 我可以看到我的OSGI包已成功部署为OSGI容器上的服务(bundle id表示ACTIVE状态,我也可以在osgi控制台上看到“Service registered”输出) .

现在我的下一步是将上述OSGI包作为服务使用 . 据我所知,为了做到这一点,我可以使用“ServiceReference” .

假设我现在正在创建一个完全 new java project (因此在这个项目的工作空间中没有链接与上面创建的链接),这样它将充当上面创建的服务的消费者 .

我的疑问是 - 我是否需要在这个新的java项目中创建HelloWorld接口的“副本”?换句话说,我需要在新项目的工作区中将此接口作为“存根”?

我问这个的原因是,如果我在新项目的工作区中没有“HelloWorld”接口的副本,我将在下面提到的第2和第3行编译错误 .

public class ConsumerActivator实现了BundleActivator {ServiceReference helloServiceReference;

public void start(BundleContext context)抛出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)抛出Exception {

context.ungetService(helloServiceReference);
}}

那么,说消费者包应该具有它打算使用的服务接口的“存根”是否正确?

对不起,如果这听起来是一个非常基本的问题,但只需澄清,因为我无法在网上任何地方找到它 . 提供的所有示例都假设使用者和服务都是相同代码工作区的一部分 .

非常感谢提前澄清 .

最诚挚的问候LB

2 回答

  • 3

    不,只需在两个项目之间创建依赖关系 .

    此外,如果刚开始使用OSGi,则不应该使用低级OSGi API . 在你学习如何编写shell脚本之前,这就是试图破解Linux内核!请从声明性服务开始...请参阅此处的教程:http://bndtools.org/tutorial.html

  • 1

    不,最佳做法是将包含接口的单独包作为API包的一部分 . 因此,您可以将接口与实际服务提供商分开 . 但是,在您的情况下,这种方法超越了顶部,我将在同一个bundle中共存HelloWorld接口及其(服务)实现 .

相关问题