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

标签 java command-line osgi equinox bnd

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

相关文章:

arrays - 在 Swift 中读取 plist 文件的内容

python - cookielib : How to save Python cookies and load it?

maven - 为 Liferay 手动创建可部署的 JAR

java - 单元测试 OSGi 服务,该服务引用了另一个服务

java - 项目 react 器: collectList() doesn't work for Flux. create()

java - RealmResults 查询返回部分结果 - Android

java - 抛出新异常

java - 消除 Java Spring 多对多关系中的循环 JSON

windows-7 - 命令行语法可防止在 PowerShell 输出文件中换行?

eclipse - 为什么 MANIFEST.MF 看不到来自 Maven 的 pom 的包?