OSGi 系列(二)之 Hello World

OSGi 系列(二)之 Hello World

之前曾介绍过 OSGi 是什么,下面将继续上篇介绍的内容,讲述一个简单的 OSGi Bundle:Hello World 是如何开发的。

在 OSGi 中,软件是以 Bundle 的形式发布的。一个 Bundle 由 Java 类和其它资源构成,它可为其它的 Bundle 提供服务,也可以导入其它 Bundle 中的 Java 包;同时,OSGi 的 Bundle 也可以为其所在的设备提供一些功能。

1. 环境准备

<dependency>
    <groupId>org.osgi</groupId>
    <artifactId>org.osgi.core</artifactId>
    <version>5.0.0</version>
</dependency>

2. 新建 Bundle

  1. 新建一个 maven 工程,并编写启动这个 bundle 的启动类 HelloBundleActivator
package com.github.binarylei;

import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;

public class HelloBundleActivator implements BundleActivator {
    @Override
    public void start(BundleContext bundleContext) throws Exception {
        System.out.println("bundle start...");
    }

    @Override
    public void stop(BundleContext bundleContext) throws Exception {
        System.out.println("bundle stop...");
    }
}
  1. 使用 maven-jar-plugin 插件生成 META-INF/MANIFEST.MF 文件,插件配制如下:
<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-jar-plugin</artifactId>
    <version>2.4</version>
    <configuration>
        <archive>
            <manifestEntries>
                <Bundle-ManifestVersion>2</Bundle-ManifestVersion>
                <Bundle-SymbolicName>com.github.binarylei.demo-osgi</Bundle-SymbolicName>
                <Bundle-Version>1.0.0</Bundle-Version>
                <Import-Package>org.osgi.framework</Import-Package>
                <Bundle-Activator>com.github.binarylei.HelloBundleActivator</Bundle-Activator>
            </manifestEntries>
        </archive>
    </configuration>
</plugin>

生成的 META-INF/MANIFEST.MF 文件内容如下,也可以手动编写:

Manifest-Version: 1.0
Bundle-SymbolicName: com.github.binarylei.demo-osgi
Bundle-Version: 1.0.0
Archiver-Version: Plexus Archiver
Built-By: len
Bundle-Activator: com.github.binarylei.HelloBundleActivator
Bundle-ManifestVersion: 2
Import-Package: org.osgi.framework
Created-By: Apache Maven 3.3.9
Build-Jdk: 1.8.0_91
  1. 生成 jar 包,其实 bundle 和普通的唯一的区别就是 META-INF/MANIFEST.MF 配制不同。

3. 运行 Bundle

  1. http://felix.apache.org/downloads.cgi 下载 felix-framework-5.6.10

  2. 解压后目录如下:

  • bin:felix 启动程序
  • bundle:启动程序时运行的 bundle
  • conf:配制文件
  • doc:文档
  • felix-cache:启动程序时运行生成的 bundle 缓存,删除后重启 felix 会丢失之前的运行信息
  1. felix 基本操作
# 运行 felix,进入 felix 安装目录,注意直接进入 bin 目录运行 jar 包会报错
java -jar bin/felix.jar
# 加载 bundle
install file:///C:/Users/len/Desktop/demo-osgi/target/demo-osgi-1.0-SNAPSHOT.jar
# 启动 bundle
start 8
# 停止 bundle
stop 8
# 卸裁 bundle
uninstall 8

图2.1 felix 基本操作

参考:

http://developer.51cto.com/art/200909/154762.htm

原文地址:https://www.cnblogs.com/binarylei/p/8535598.html