1、 定义服务
获取 [r1] OSGi的一个eclipse实现。
在sample.http插件中,编写一个接口UserService, 并把它的package包export暴露给其他插件。
2、 服务组件Component
1> 使用事件策略(像依赖注入的set方式)
(1)新建Helper类,作为服务组件实现;
public class UserHelper {
public UserHelper() {
}
private static UserHelper INSTANCE;
public static UserHelper getInstance() {
return INSTANCE;
}
protected void activate() {
System.out.println("activate " + this);
INSTANCE = this;
}
protected void deactivate() {
System.out.println("deactivate " + this);
INSTANCE = null;
}
private UserService service;
public UserService getService() {
return service;
}
protected void setService(UserService manager) {
System.out.println("register user-service : " + manager);
this.service = manager;
}
protected void unSetService(UserService manager) {
System.out.println("unregister user-service : " + manager);
this.service = null;
}
}
(2)添加org.eclipse.equinox.ds插件的依赖;
(3)在OSGI-INF目录下新建组件New->Plug-in Development->Component Defintion。在MANIFEST.MF中添加Service-Component 属性,指定该 Bundle 应用的服务组件配置文件;
reference参数含义请查看这里。
2> 使用lookup策略,在上下文中通过name获得服务。
3、 绑定(实现)服务
(1) 新建插件sample.http.user.en插件,然后添加sample.http和org.eclipse.equinox.ds的依赖;
(2) 实现UserService接口。
(3) 新建Component Defintion,绑定到服务。
4、 测试
运行/sample.server/server-web.product,打开浏览器http://localhost/helloworld?username=test
源码:
[r1]简单的OSGi :https://github.com/winse/hello/tree/ca902237e03c05f13c7a3cf838de48c825d98dc4
[r2]实现后的DS版本: https://github.com/winse/hello/tree/5ffea88d723bae34099d6c94686436dc8fd2eb28
参考资料:
1: 利用 Eclipse 开发基于 OSGi 的 Bundle 应用(使用代码注册服务)
http://www.ibm.com/developerworks/cn/opensource/os-ecl-osgibdev/index.html
2: OSGi 中的 Declarative Services 规范简介
http://www.ibm.com/developerworks/cn/opensource/os-ecl-osgids/index.html
3: Getting Started with OSGi: Declarative Services and Dependencies (这一篇文章太正了!同时是一篇CommandProvider的实现)
http://www.eclipsezone.com/eclipse/forums/t97690.rhtml
4: Getting Started with OSGi: Introducing Declarative Services
http://www.eclipsezone.com/eclipse/forums/t96740.html
5: Declarative Services规范简介及应用
http://marsvaadin.iteye.com/blog/1678286
6: OSGi 中的 Declarative Services 规范简介
http://www.ibm.com/developerworks/cn/opensource/os-ecl-osgids/index.html