osgi模块交互实例

osgi模块间交互有两种方式:导出包方式,与服务方式,导出包方式比较简单,因此只给出实例。
一般模块之间的交互是单向的。假设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!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值