osgi模块间交互有两种方式:导出包方式,与服务方式,导出包方式比较简单,因此只给出实例。
一般模块之间的交互是单向的。假设A使用B项目中的某个功能
新建插件项目B,项目B结构图:
[img]http://dl.iteye.com/upload/attachment/465416/ba452bde-cfc5-326b-b0c5-8992a8101f04.jpg[/img]
HelloService是其他模块需要的服务的接口类
其实现类为HelloComponent
新建插件项目A,项目结构如下:
[img]http://dl.iteye.com/upload/attachment/465414/b681a308-5198-39fd-95c2-37757159cb1a.jpg[/img]
以osgi框架运行模块A,结果:
osgi> osgi bundle started
in util
hello world!
一般模块之间的交互是单向的。假设A使用B项目中的某个功能
新建插件项目B,项目B结构图:
[img]http://dl.iteye.com/upload/attachment/465416/ba452bde-cfc5-326b-b0c5-8992a8101f04.jpg[/img]
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 {
@Override
public 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 {
}
}
新建插件项目A,项目结构如下:
[img]http://dl.iteye.com/upload/attachment/465414/b681a308-5198-39fd-95c2-37757159cb1a.jpg[/img]
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");
}
}
以osgi框架运行模块A,结果:
osgi> osgi bundle started
in util
hello world!