OSGI学习(1) - HelloWorld

工作后第一个项目就用的OSGI。连Java都不怎么会,一下子就用OSGI,各种概念名词都不懂,而且没有时间去深入学习,只能在已经搭好的框架上写交易,写业务流程,数据库的增删改查,过了很久才慢慢理解。

这个系列的笔记主要以实例的方式介绍我们项目中用到的OSGI技术和原理,主要包括OSGI的HelloWorld,OSGI的服务封装与发布,OSGI与Spring的结合SpringDM,OSGI的类加载原理,OSGI的测试。因为许多新来的同事可能没接触过OSGI,可以让他们按这个笔记学习一下。


OSGI HelloWorld



(1) 打开Eclipse,新开一个Workspace,新建一个Plug-in Project

OSGI学习(1) - HelloWorld


(2) 需要选择一个FrameWork

OSGI学习(1) - HelloWorld

(3) 选择生成一个activator

OSGI学习(1) - HelloWorld

(4) 不用选模板,直接Finish

OSGI学习(1) - HelloWorld

(5) 一个OSGI的bundle就建好了。

OSGI学习(1) - HelloWorld

(6) 修改Activator的代码

public class
Activator implements BundleActivator {
 
    private static BundleContext context;
 
    static BundleContext getContext() {
        return context;
    }
 
    public
    void start(BundleContext bundleContext) 
          throws Exception {
        Activator.context = bundleContext;
        System.out.println("Hello World");
    }
 
    public
    void stop(BundleContext bundleContext) 
        throws Exception {
        Activator.context = null;
        System.out.println("Goodbye World");
    } 
}

(7) 点击Run->Debug Configuration,新建一个OSGI的configuration

OSGI学习(1) - HelloWorld


(8) 把图中的Target Platform了的bundle选中,然后Debug

OSGI学习(1) - HelloWorld

(9) 程序起来了,使用ss命令查看bundle状态,然后停止我们自己写的bundle,再启动,就看到Hello World和Goodbye World了。

OSGI学习(1) - HelloWorld


本文转自nxlhero 51CTO博客,原文链接:http://blog.51cto.com/nxlhero/1661534,如需转载请自行联系原作者