OSGi应用中自动启动bundle

开发 后端
本文讲述OSGi应用中如何自动启动bundle。作者发现应用启动的时候,几乎所有 bundle 都处于 Resolved 状态,而不是 Started 状态。本文逐步介绍了如何将所有bundle启动的方法。

OSGi即Java模块系统,而OSGi bundle则是OSGi中软件发布的形式。本文讲述OSGi应用中如何自动启动bundle。作者最近开发了一个 OSGi 的应用,部署之后发现,当应用启动的时候,几乎所有 bundle 都处于 Resolved 状态,而不是 Started 状态。

51CTO编辑推荐:OSGi入门与实践全攻略

怎样启动bundle 呢?有如下几种方法 :

1. 手工启动bundle,即在 console 中使用命令 start N 来逐个启动所有bundle,其中 N 表示每个 bundle 的 id

这种方法过于麻烦,要耗费大量时间,因此不可取。

2.在配置文件中声明为自动启动bundle。在 WEB-INF\eclipse\configuration 中的 config.ini 中,如下配置:

osgi.bundles=bundle1@start, bundle2@start,......bundleN@start

这种方法可以自动启动所有bundle,但是写起来仍然比较麻烦,需要把所有bundle 一个一个都配置为@start。

3. 在应用的所有bundle 中选择一个bundle,将其在 config.ini 中配置为自动启动,然后在这个bundle 中,再把

应用的所有其他bundle 启动起来。假定该bundle 的Activator 类为 OSGiStartingBundleActivator, 代码如下:

  1. public class OSGiStartingBundleActivator implements BundleActivator  
  2. {  
  3.     public static BundleContext bundleContext = null;  
  4.       
  5.     public void start(BundleContext context) throws Exception  
  6.     {  
  7.         bundleContext = context;  
  8.          
  9.         // start bundles if it has been installed and not started  
  10.         Bundle[] allBundles = context.getBundles();  
  11.         for (int i=0; i<allBundles.length; i++)  
  12.         {  
  13.             int currState = allBundles[i].getState();  
  14.             if ( Bundle.ACTIVE != currState && Bundle.RESOLVED==currState  )  
  15.             {  
  16.                     System.out.println("starting bundle : " + allBundles[i].getSymbolicName());  
  17.  
  18.                     try 
  19.                     {  
  20.                             allBundles[i].start();  
  21.                     }  
  22.                     catch (BundleException e)  
  23.                     {  
  24.                             e.printStackTrace();  
  25.                     }  
  26.               }  
  27.           }  
  28.     }  
  29.  
  30.     public void stop(BundleContext context) throws Exception  
  31.     {  
  32.     }  
  33.  }  
  34.  

【编辑推荐】

  1. OSGi入门与实践全攻略
  2. 你好,OSGi!OSGi入门必读系列
  3. OSGi与Spring:设置Spring DM开发环境
  4. OSGi和Spring入门:什么是Spring动态模型(Spring DM)?
  5. OSGi是什么:Java语言的动态模块系统
责任编辑:yangsai 来源: 博客园
相关推荐

2009-09-16 17:15:19

OSGi Bundle

2009-09-17 11:19:34

OSGi依赖性管理

2009-06-16 13:49:53

ServiceMix4OSGi

2012-06-25 11:47:14

ibmdw

2017-09-21 10:43:55

web程序语言

2009-12-21 13:34:41

OSGi

2018-05-25 15:26:28

Windows 10Windows自动启动

2009-03-03 10:06:00

IBMJavaOSGi

2009-09-28 13:32:39

OSGi入门

2009-10-15 15:12:39

Equinox服务器端Equinox

2009-06-10 18:12:38

Equinox动态化OSGi动态化

2009-06-01 11:12:34

OSGi规范架构体系结构

2010-04-07 08:55:00

OSGiSpring

2009-10-22 11:03:20

OSGi Web应用程

2011-07-07 17:30:25

iPhone Xcode

2009-06-18 10:03:57

EquinoxOSGi应用服务器

2009-10-19 14:14:19

OSGi Web应用

2009-06-01 11:37:46

EquinoxOSGi服务器

2009-06-01 11:20:21

OSGi服务规范非赢利机构

2009-06-01 11:09:16

OSGI实战进阶
点赞
收藏

51CTO技术栈公众号