1. 创建一个Bundle工程,在STS中创建一个Plug-in Project,单击Next按钮。
2.设置工程属性,输入相关的信息,在Target Platfrom选项框中,选择an OSGi framework的stardard选项,也就是建立一个标准的OSGi Bundle工程,单击Next按钮。
3.输入Bundle的相关元数据信息,单击Next按钮。
4.模版设置,去掉Create a plug-in using one of the templates,单击Finish按钮。
5.完成Bundle工程的创建后,可以看到如下的工程视图。
6.打开Activator类,可以看到里面有一个start方法和一个stop方法,可以在bundle启动和停止的时候做一些事情。这里只是简单地输出一个字符串,作为bundle启动和停止时的标识。
package helloosgi;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
public class Activator implements BundleActivator {
private static BundleContext context;
static BundleContext getContext() {
return context;
}
/*
* (non-Javadoc)
* @see org.osgi.framework.BundleActivator#start(org.osgi.framework.BundleContext)
*/
public void start(BundleContext bundleContext) throws Exception {
Activator.context = bundleContext;
System.out.println("Start OSGi...");
}
/*
* (non-Javadoc)
* @see org.osgi.framework.BundleActivator#stop(org.osgi.framework.BundleContext)
*/
public void stop(BundleContext bundleContext) throws Exception {
Activator.context = null;
System.out.println("Stop OSGi...");
}
}
7.代码写好后,导出插件工程发布,右击HelloOSGi工程-->Export,选择Plug-in Development的Deployable plug-ins and fragments,单击Next按钮。
8.选择要导出的插件,Destination选项卡的Directory选择Felix环境的物理地址,导出后,会在Felix工程的根目录自动创建一个felix-cache和plugins目录,bundle会默认导出这个目录,单击Finish按钮。
9.刷新Felix工程,多了felix-cache和plugins目录,我们所导出的bundle就在plugins里面。
10.安装运行HelloOSGi
启动Felix,在Console中先使用install命令安装bundle,接着使用start命令启动bundle。
启动的时候,start命令后接着那个bundle的启动ID就可以启动bundle。
停止的时候,stop命令后接着那个bundle的ID就可以停止bundle。
11.卸载HelloOSGi
使用uninstall命令卸载一个bundle,用法如install命令。