前1篇博文中我們講授了OSGI的傳統注冊式服務與聲明式服務,再前1篇我們我們進行了osgi + felix example2的編寫,這1篇博文我們編寫了1個Bundle和1個接口并對這個接口進行了相應的實現以后,在這個bundle的start方法中進行了該服務的注冊,并沒有使用這個服務。本文中編寫的程序依然是不使用這個服務,只進行相應的注冊,在example3中將會講授使用這個服務。
程序中變動的只是Activator中1部份內容,具體的程序以下:
package cn.com.example2b;
import cn.com.example2.DictionaryService;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import java.util.Dictionary;
import java.util.Hashtable;
/**
* Created by Administrator on 2016/6/19.
*/
public class Activator implements BundleActivator {
public void start(BundleContext context) throws Exception {
Hashtable<String, String> props = new Hashtable<String, String>();
props.put("Language", "French");
context.registerService(DictionaryService.class.getName(), new DictionaryImpl(), props);
System.out.println("service registered...");
}
public void stop(BundleContext context) throws Exception {
}
private static class DictionaryImpl implements DictionaryService {
String[] m_dictionary = {
"bienvenue", "au", "tutoriel", "osgi"
};
public boolean checkWord(String word) {
word = word.toLowerCase();
for (int i = 0;i < m_dictionary.length; i++) {
if (m_dictionary[i].equals(word)) {
return true;
}
}
return false;
}
}
}
相對example2來講,變動的只是Bundle啟動方法中,在進行服務注冊的時候傳入的參數不同,預計felix官網這么做的緣由是要我們熟習osgi注冊式服務,本文也其實不進行相應服務的使用,但本文中,個人有1些其他的想法,就是這個DictionaryService的實現類其實可以單獨抽取出來,單獨使用,由于在后文中幾近每一個Bundle中都有這個接口的實現類,雖然m_dictionary有所不同,這些將在example6中單獨抽取出來使用,由于后文中我對服務注冊的使用和felix官網所說有所不同,這些到時候再說,這1節不再討論。