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
總結
以上是生活随笔為你收集整理的bndtools教程的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: GPU Gems1 - 14 透视阴影贴
- 下一篇: GPU Gems1 - 15 逐像素光照