我对Java OSGi框架是个新手。我在这里遵循一个示例教程:https://o7planning.org/en/10135/java-osgi-tutorial-for-beginners
我有一个提供基本数学函数的MathService包和一个使用MathService包的MathConsumer包。这些包将从MathService包中正确导出,并为MathConsumer包正确设置依赖项。
由于某种原因,MathConsumer激活器中的context.getServiceReference调用返回null,导致了一个异常,我不明白为什么。下面是我的文件。有人会有这方面的经验吗?
MathConsumer Activator.java:
package org.o7planning.tutorial.helloosgi.mathconsumer;
import org.o7planning.tutorial.helloosgi.mathservice.MathService;
import org.o7planning.tutorial.helloosgi.utils.MathUtils;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceReference;
public class Activator implements BundleActivator {
private static BundleContext context;
static BundleContext getContext() {
return context;
}
public void start(BundleContext bundleContext) throws Exception {
Activator.context = bundleContext;
System.out.println("MathConsumer Starting...");
System.out.println("5-3 = " + MathUtils.minus(5, 3));
//
ServiceReference<?> serviceReference=context.getServiceReference(MathService.class);
if (serviceReference == null) {
System.out.println("serviceReference is null"); // THE PROBLEM IS HERE
}
MathService service = (MathService)context.getService(serviceReference);
if (service == null) {
System.out.println("MathService service is null");
}
System.out.println("Got Mathservice service");
System.out.println("5+3 = " + service.sum(5, 3));
System.out.println("MathConsumer Started");
}
public void stop(BundleContext bundleContext) throws Exception {
Activator.context = null;
System.out.println("MathConsumer Stopped");
}
}MathService Activator.java
package org.o7planning.tutorial.helloosgi;
import org.o7planning.tutorial.helloosgi.mathservice.MathService;
import org.o7planning.tutorial.helloosgi.mathservice.impl.MathServiceImpl;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
public class Activator implements BundleActivator {
private static BundleContext context;
static BundleContext getContext() {
return context;
}
public void start(BundleContext bundleContext) throws Exception {
Activator.context = bundleContext;
System.out.println("Registry Service MathService...");
this.registryMathService();
System.out.println("OSGi MathService Started");
}
private void registryMathService() {
MathService service = new MathServiceImpl();
context.registerService(MathService.class, service, null);
}
public void stop(BundleContext bundleContext) throws Exception {
Activator.context = null;
System.out.println("OSGi MathService Stopped!");
}
}发布于 2019-08-23 07:21:22
这是一个古老的教程。我强烈建议你忘记这件事。
该代码有许多问题,其中最大的问题是:
MathService将在MathConsumer之前启动,因此,服务在被请求时不可用(null)是完全没有问题的。如果您确实需要在激活器中执行此操作,那么您应该查看ServiceTracker并从一个线程调用服务,该线程可以等待服务注册,而不会阻塞激活器。
但是,使用Declarative Services using annotations可以更轻松地做到这一点。
如果你只是想学习OSGi,我建议你从enRoute开始。
https://stackoverflow.com/questions/57614898
复制相似问题