Freud's Blog

Stay hungry, stay foolish. 少年辛苦终身事,莫向光阴惰寸功。

JAVA OSGi(四)-模块化的OSGI

Posted on By Freud Kang

  • 新建一个plug-in project,命名为osgi_equinox_provider

new provider project

  • com.freud.osgi包下新建一个HelloWorldService的接口
package com.freud.osgi;

public interface HelloWorldService {

	String sayHello(String name);
}
  • 新建一个plug-in project,命名为osgi_equinox_impl

new implement project

  • 修改META-INF下的文件MANIFEST.MF,在import-package上添加com.freud.osgi

import package

  • com.freud.osgi.impl下添加一个类HelloWorldServiceImpl,内容为
package com.freud.osgi.impl;

import com.freud.osgi.HelloWorldService;

public class HelloWorldServiceImpl implements HelloWorldService {

	@Override
	public String sayHello(String name) {
		String ret = "Hello " + name;
		System.out.println(ret);
		return ret;
	}

}
  • com.freud.osgi.impl下修改Activator类为如下内容
package com.freud.osgi.impl;

import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;

import com.freud.osgi.HelloWorldService;

public class Activator implements BundleActivator {

	private static BundleContext context;

	static BundleContext getContext() {
		return context;
	}

	public void start(BundleContext bundleContext) throws Exception {
		Activator.context = bundleContext;
		context.registerService(HelloWorldService.class,
				new HelloWorldServiceImpl(), null);
	}

	public void stop(BundleContext bundleContext) throws Exception {
		context.ungetService(context
				.getServiceReference(HelloWorldService.class));
		Activator.context = null;
	}
}
  • 新建一个plug-in project,命名为osgi_equinox_consumer

new consumer project

  • 修改META-INF目录下的MANIFEST.MF文件为

import consumer package

  • 修改com.freud.osgi.consumer目录下的Activator文件内容为
package com.freud.osgi.consumer;

import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceReference;

import com.freud.osgi.HelloWorldService;

public class Activator implements BundleActivator {

	private static BundleContext context;

	static BundleContext getContext() {
		return context;
	}

	public void start(BundleContext bundleContext) throws Exception {
		Activator.context = bundleContext;
		ServiceReference<HelloWorldService> serviceReference = context.getServiceReference(HelloWorldService.class);
		
		HelloWorldService service = context.getService(serviceReference);
		
		service.sayHello("world from equinox consumer---");
	}

	public void stop(BundleContext bundleContext) throws Exception {
		Activator.context = null;
	}

}
  • osgi_equinox_provider项目上右键->run as->Run configurations-new OSGi FrameWork

run configuration

  • 得出的控制台输出如下

ss stdout


参考资料

视频教程 : http://v.youku.com/v_show/id_XNDE1NzU0OTY0.html
Equinox OSGi官网 : http://www.eclipse.org/equinox/
林昊 : 《OSGi原理与最佳实践》
Richard S. Hall : 《OSGi实战》