在Eclipse中開發OSGi(3)在Felix環境中運行Bundle

前面搭建了一個Apache Felix的運行環境,下面就寫一個簡單的bundle,測試測試。

1、新建一個插件工程,如下圖:

點擊下一步。

2、給插件工程命名一個名字,這裏叫pig1。This plug-in is targeted to run with中選擇an OSGI framework -->standard,如下圖紅框中所示:

點擊下一步。

3、bundle中有一個啓動類,默認是Activator,相當於普通工程中的Main類。你也可以把它更改成其他名字,這裏使用默認的名字。如下圖:

點擊下一步。

4、去掉Create a plug-in using one of the templates,如下圖:

點擊Finish。

5、插件工程建好後,打開Activator類,可以看到裏面有一個start方法和一個stop方法,可以在bundle啓動和停止的時候做一些事情。這裏只是簡單地輸出一個字符串,作爲bundle啓動和停止時的標識。

    /*  
         * (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 pig1" );  
        }  
      
        /*  
         * (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 pig1" );  
        }  
 6、代碼也寫好後,就可以導出插件工程發佈了。如何讓這個工程作爲一個bundle被部署到Felix容器中呢?右擊插件工程pig1,選擇Export。可看下圖:

出現Export視圖之後,選擇Plug-in Development下的Deployable plug-ins and fragments,如下圖:

點擊下一步,選擇要導出的插件,Destination選項卡的Directory選擇我們的Felix環境的物理地址,導出後,會在Felix工程的根目錄自動創建一個plugins目錄,bundle會默認導出這個目錄。如下圖:

點擊Finish,你就可以看到Felix工程下面多了一個plugins目錄,我們所導出的bundle就在裏面,如下圖:

7、接着就是安裝、運行了。

有三種方法可以安裝、運行一個bundle。

(1)使用命令。

首先,啓動Felix,在Console中先使用install命令安裝bundle,接着使用start命令啓動bundle,如下圖:

啓動的時候,start命令後接着那個bundle的啓動ID就可以啓動bundle了,如上圖的12。

可以看到,當啓動bundle的時候,輸出了Activator類中start方法的輸出語句,即"start pig1"。

Pig1的狀態爲Active,說明bundle啓動成功了。

當然,你也可以使用uninstall命令卸載一個bundle,用法如install命令。

 

(2)使用Felix配置文件,打開conf/config.properties,如下圖:


打開config.properties,找到felix.auto.start.1參數,值寫成file:plugins/pig1_1.0.0.201109291700.jar,如:

(如果你有多個bundle,之間用空格隔開)。

    # The following property is a space-delimited list of bundle URLs  
    # to install and start when the framework starts. The ending numerical  
    # component is the target start level. Any number of these properties  
    # may be specified for different start levels.  
    felix.auto.start.1 =file:plugins/pig1_1. 0.0 . 201109291700 .jar  
參數寫好後,啓動Felix,你就可以看到bundle Pig1自動安裝並啓動了,如下圖所示:

(3)第三種方法就是使用File Install了,使用Apache Felix的File Install bundle,我們可以安裝和啓動bundle而無需啓動Felix,這個將在下面的章節中講解。

 

8、OK,完成了。


轉自:http://marsvaadin.iteye.com/blog/1591273


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章