在执行某些代码后关闭 OSGi 容器(以创建命令行工具)



我想创建一个启动OSGi框架的命令行工具,以便重用依赖于OSGi的代码。

在从OSGi包访问命令行参数的答案中,我得到了如何读取命令行参数:

@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[] {};
}
}
}

但是现在当我像这样运行组装好的罐子(bnd-export-maven-plugin(时:

java -jar <path-to>/application.jar lorem ipsum

我得到了预期的输出,但应用程序没有终止。

在阅读了 4.2.6 停止框架之后,我想我需要在系统捆绑包上调用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();
}
}

但它似乎不是这样工作的。

如果您希望系统捆绑包停止,则必须这样做(注意 0(:

bundleContext.getBundle(0).stop();

要正确执行此 hyper,您应该在另一个线程中执行此操作。

@Component
public class ServiceComponent {
@Activate
void activate(BundleContext c) {
CompletableFuture.runAsync( ()-> {
try {
c.getBundle(0).stop();
} catch (BundleException e) {
e.printStackTrace();
}
} );        
}
}

当然,这是自杀的组成部分...

最新更新