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

- 在
com.freud.osgi包下新建一个HelloWorldService的接口
package com.freud.osgi;
public interface HelloWorldService {
String sayHello(String name);
}- 新建一个
plug-in project,命名为osgi_equinox_impl

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

- 在
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

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

- 修改
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

- 得出的控制台
输出如下

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