osgi模块交互实例
osgi模块间交互有两种方式:导出包方式,与服务方式,导出包方式比较简单,因此只给出实例。
一般模块之间的交互是单向的。假设A使用B项目中的某个功能
新建插件项目B,项目B结构图:
HelloService是其他模块需要的服务的接口类
其实现类为HelloComponent
package cn.org.osgi.ppt.service;public interface HelloService {public void sayHello();}
package org.osgi.ppt.service.component;import cn.org.osgi.ppt.service.HelloService;public class HelloComponent implements HelloService {@Overridepublic void sayHello() {System.out.println("hello world!");}}
package b;import org.osgi.framework.BundleActivator;import org.osgi.framework.BundleContext;import org.osgi.ppt.service.component.HelloComponent;import cn.org.osgi.ppt.service.HelloService;public class Activator implements BundleActivator {/* * (non-Javadoc) * @see org.osgi.framework.BundleActivator#start(org.osgi.framework.BundleContext) */public void start(BundleContext context) throws Exception {//服务提供方负责,注册服务context.registerService(HelloService.class.getName(), new HelloComponent(), null); //注册服务}/* * (non-Javadoc) * @see org.osgi.framework.BundleActivator#stop(org.osgi.framework.BundleContext) */public void stop(BundleContext context) throws Exception {}}
package a;import org.osgi.framework.BundleActivator;import org.osgi.framework.BundleContext;import org.osgi.framework.ServiceReference;import cn.org.osgi.ppt.service.HelloService;import export.Util;public class Activator implements BundleActivator {/* * (non-Javadoc) * * @see * org.osgi.framework.BundleActivator#start(org.osgi.framework.BundleContext * ) */public void start(BundleContext context) throws Exception {// 自己写的System.out.println("osgi bundle started");Util.printString(); // 使用导出包进行模块交互// 服务使用方,使用服务,先获取服务引用,再获取服务,使用服务方式进行模块之间的交互ServiceReference hs = context.getServiceReference(HelloService.class.getName());HelloService hservice = (HelloService) context.getService(hs);hservice.sayHello();}/* * (non-Javadoc) * * @see * org.osgi.framework.BundleActivator#stop(org.osgi.framework.BundleContext) */public void stop(BundleContext context) throws Exception {// 自己写的System.out.println("osgi bundle stopped");}}