这两个问题的解决方案是在加载我自己的包之前将“scr”jar(用于解析声明性服务)作为包加载。
因为 jar 位于我的 maven 存储库中并且它应该跨系统工作,所以以下代码从 scr jar 所在的任何位置加载:
URL url = getClass().getClassLoader().getResource("org/apache/felix/scr/ScrService.class");
String jarPath = url.toURI().getSchemeSpecificPart().replaceAll("!.*", "");
framework.getBundleContext().installBundle(jarPath).start();
在此之后,我加载了自己的包,并且正确检测到其中的服务。
在旁注中,您可以通过向初始映射添加一些属性来启用日志记录:
map.put("ds.showtrace", "true");
map.put("ds.showerrors", "true");
更多属性可以在http://felix.apache.org/documentation/subprojects/apache-felix-service-component-runtime.html找到
为了将来参考,这里是我用来启动和运行它的所有代码
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);
// more properties available at: http://felix.apache.org/documentation/subprojects/apache-felix-service-component-runtime.html
map.put("ds.showtrace", "true");
map.put("ds.showerrors", "true");
System.out.println("Building OSGi Framework");
FrameworkFactory frameworkFactory = ServiceLoader.load(FrameworkFactory.class).iterator().next();
Framework framework = frameworkFactory.newFramework(map);
System.out.println("Starting OSGi Framework");
framework.start();
// declarative services dependency is necessary, otherwise they won't be picked up!
loadScrBundle(framework);
framework.getBundleContext().installBundle("file:/path/to/myBundle.jar").start();
ServiceReference reference = framework.getBundleContext().getServiceReference("my.Interface");
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);
}
}
}
private void loadScrBundle(Framework framework) throws URISyntaxException, BundleException {
URL url = getClass().getClassLoader().getResource("org/apache/felix/scr/ScrService.class");
if (url == null)
throw new RuntimeException("Could not find the class org.apache.felix.scr.ScrService");
String jarPath = url.toURI().getSchemeSpecificPart().replaceAll("!.*", "");
System.out.println("Found declarative services implementation: " + jarPath);
framework.getBundleContext().installBundle(jarPath).start();
}