我正在尝试运行一个 maven OSGi 捆绑项目,但我得到:
Exception in thread "main" java.lang.NullPointerException: Specified service reference cannot be null.
在System.out.println(framework.getBundleContext().getService(reference));
下面initialize()
。
我似乎无法正确处理。我是 OSGi 的新手。请帮助我让项目运行。谢谢大家。
这是我嵌入我的 OSGi 框架的方式,然后尝试启动服务:
private void initialize() throws BundleException, URISyntaxException {
Map<String, String> map = new HashMap<String, String>();
// make sure the cache is cleaned
map.put(Constants.FRAMEWORK_STORAGE_CLEAN, Constants.FRAMEWORK_STORAGE_CLEAN_ONFIRSTINIT);
map.put("ds.showtrace", "true");
map.put("ds.showerrors", "true");
FrameworkFactory frameworkFactory = ServiceLoader.load(FrameworkFactory.class).iterator().next();
Framework framework = frameworkFactory.newFramework(map);
System.out.println("Starting OSGi Framework");
framework.init();
framework.start();
loadScrBundle(framework);
framework.getBundleContext().installBundle("file:" + "D:/core-1.0.jar").start();
ServiceReference<?> reference = framework.getBundleContext()
.getServiceReference(HelloWorldService.class.getName());
System.out.println(framework.getBundleContext().getService(reference));
for (Bundle bundle : framework.getBundleContext().getBundles()) {
System.out.println("Bundle: " + bundle.getSymbolicName());
if (bundle.getRegisteredServices() != null) {
for (ServiceReference<?> serviceReference : bundle.getRegisteredServices())
System.out.println("\tRegistered service: " + serviceReference);
}
}
}
这是我导出rev.core.api
服务包的方式:
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.0.2</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.felix</groupId>
<artifactId>maven-bundle-plugin</artifactId>
<extensions>true</extensions>
<configuration>
<instructions>
<Bundle-SymbolicName>${project.name}</Bundle-SymbolicName>
<Export-Package>rev.core.api</Export-Package>
<Bundle-Activator>rev.core.impl.Activator</Bundle-Activator>
<Bundle-Vendor>Rev CAIT</Bundle-Vendor>
</instructions>
</configuration>
</plugin>
</plugins>
</build>