bndtools教程

使用工具编程的确能给人们带来很多便利,但是在不会用之前,且缺乏相应的中文资料让你去了解时,真是一种折磨,同时也是一种挑战。

bndTools其实就是用来开发OSGi的一个工具,它为开发提供了便利,具体是哪些便利,在在这里就不细说了。

花了一个星期,终于把bndtools的程序和逻辑整理清楚,不想说太多细节,先看整体框架。

bndtools主要分为三部分:

1.api,也就是提供服务的一个接口(我们可以把它理解为菜单)

2.impl,对接口的具体实现(可以指菜单上具体某个菜的做法,人家在后厨已经做好了)

3.command,也就是用具体命令调用此服务(可以理解为客户点菜)

了解了这三部分之后我们就可以写程序了:

1.在eclipse上安装bndTools

2.写一个api程序,我写的是com.example.api

package com.example.api;

/**
 * @author Joye Luo
 */
public interface Greeting {
    public String sayHello(String name);
}

在bnd.bnd文件中把它添加为导出包,因为等下写其它bundle的时候会需要依赖它,这其实就是OSGi的一个模块化机制,实现了低耦合。

3.写一个实现程序,我写的是com.example.impls

package com.example.impls;

import org.osgi.service.component.annotations.*;

import com.example.api.Greeting;

/**
 * @author Joye Luo
 */
@Component
public class GreetingImpl implements Greeting {
    @Override
    public String sayHello(String name) {
        return "Hello " +name;
    }
}

@Component注释可以提供注册服务的功能,因为在这里依赖了api,所以要在它的bnd.bnd文件Build Path中加上com.example.api这个包

4.写一个command程序,让它调用这个服务,我把它放在com.example.impls下的com.example.impls.command包下,其实也可以另起一个程序,我比较懒。

import org.apache.felix.service.command.CommandProcessor;

import com.example.api.Greeting;

import aQute.bnd.annotation.component.Component;
import aQute.bnd.annotation.component.Reference;

/**
 * @author Joye Luo
 */
@Component(properties={
    CommandProcessor.COMMAND_SCOPE+":String=example",
    CommandProcessor.COMMAND_FUNCTION+":String=greet"
},
provide=Object.class)
public class Command {
private Greeting greeting;

public void greet(String name){
    System.out.println("return:"+greeting.sayHello(name));
}

@Reference
public void setUserService(Greeting greeeting){
    this.greeting = greeeting;
}

}

这就会出现一个问题,在一个目录结构下,怎么让它打包出两个jar包出来,右键->new->bnd descriptor file,为这两个包配置两个不同的bnd文件就好啦。

4.最后一步就是运行它啦,随便建一个项目,我建的是com.example.client,new->bndrun file,把你要运行的bundle都添加进去,点Run OSGi,就可以打开Console了,输入命令:greet joye(随便其他什么字符串都可以)

可以看到输出为Hello joye

所有功能都完成啦,是不是很简答呢,接下来,show u the code

https://github.com/JoyeLuo/osgi-example

posted @ 2016-10-26 18:36  Hibou  阅读(1838)  评论(0编辑  收藏  举报