gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 01:41:48 24 4
gpt4 key购买 nike

我想创建一个启动 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com