《深入理解OSGi:Equinox原理、应用与最佳实践》一3.6 Bundle上下文

    xiaoxiao2022-05-14  173

    3.6 Bundle上下文

    OSGi容器中运行的各个Bundle共同构成了一个微型的生态系统,Bundle的许多行为都无法孤立进行,必须在特定的上下文环境中才有意义,因为要与上下文的其他Bundle或OSGi框架进行互动。在代码中使用BundleContext对象来代表上下文环境,当Bundle启动的时候,OSGi框架就创建这个Bundle的BundleContext对象,直到Bundle停止运行从OSGi容器卸载为止。Bundle在进行以下操作时,需要通过BundleContext对象来完成。安装一个新的Bundle到当前OSGi容器之中(BundleContext.installBundle()方法)。从当前OSGi容器中获取已有的Bundle(BundleContext.getBundle()方法)。在OSGi容器中注册服务(BundleContext.registerService()方法)。从当前OSGi容器中获取已有的服务(BundleContext.getService()方法)。在OSGi容器中注册事件监听器(BundleContext.addBundleListener()、Bundle- Context.addFrameworkListener()方法)。从Bundle的持久储存区中获取文件(BundleContext.getDataFile()方法)。获取Bundle所处环境的环境属性(BundleContext.getProperty()方法)。每个Bundle的BundleContext对象都是在调用Bundle.start()方法时由OSGi框架创建并以方法参数的形式传入到Bundle中,实现Bundle时一般会把这个对象的引用保留起来,以便在Bundle其他代码中使用,示例如下:

    public class Activator implements BundleActivator { private static BundleContext context; // Bundle中其他代码调用Activator.getContext()方法获取 // BundleContext对象 public static BundleContext getContext() { return context; } public void start(BundleContext bundleContext) throws Exception { // 将BundleContext对象的引用保留起来 Activator.context = bundleContext; } }

    上下文对象涉及Bundle的数据安全和资源分配,它应当是Bundle私有的,不应当传递给其他Bundle使用。在Bundle的stop()方法执行完之后,Bundle对象就会随之失效,如果在Bundle停止后继续使用BundleContext对象,那么OSGi框架就会抛出IllegalStateException异常。

    相关资源:七夕情人节表白HTML源码(两款)

    最新回复(0)