我想创建一个启动 OSGi 框架的命令行工具,以便重用依赖 OSGi 的代码。
在答案中accessing command-line arguments from OSGi bundle ,我知道如何读取命令行参数:
@Component
public class Example {
String[] args;
@Activate
void activate() {
System.out.println("Hello World");
System.out.println(args.length + " args:");
for (String s : args) {
System.out.println(" - " + s);
}
}
@Reference(target = "(launcher.arguments=*)")
void args(Object object, Map<String, Object> map) {
if (map.containsKey("launcher.arguments")) {
args = (String[]) map.get("launcher.arguments");
} else {
args = new String[] {};
}
}
}
但是现在当我像这样运行组装的 jar (bnd-export-maven-plugin
) 时:
java -jar <path-to>/application.jar lorem ipsum
我得到了预期的输出,但应用程序没有终止。
读完 4.2.6 Stopping a Framework 后,我想我需要在系统包上调用 stop()
。我尝试将代码更改为:
@Activate
void activate(BundleContext bundleContext) {
System.out.println("Hello World");
System.out.println(args.length + " args:");
for (String s : args) {
System.out.println(" - " + s);
}
try {
bundleContext.getBundle().stop();
} catch (BundleException e) {
e.printStackTrace();
}
}
但它似乎不是这样工作的。
最佳答案
如果您希望系统 bundle 停止,您必须执行以下操作(注意 0):
bundleContext.getBundle(0).stop();
要正确执行此 super 操作,您应该在另一个线程中执行此操作。
@Component
public class ServiceComponent {
@Activate
void activate(BundleContext c) {
CompletableFuture.runAsync( ()-> {
try {
c.getBundle(0).stop();
} catch (BundleException e) {
e.printStackTrace();
}
} );
}
}
这当然是自杀成分......
关于java - 执行某些代码后关闭 OSGi 容器(以创建命令行工具),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59677683/