OSGi 即 Java 模組系統,Bundle 為軟體發布單元。近期開發 OSGi 應用部署後發現:啟動時幾乎所有 Bundle 均處於 Resolved 狀態而非 Started。如何自動啟動 Bundle?
在 Console 執行 start N 逐個啟動(N 為 Bundle ID)。耗時費力,不可取。
在 WEB-INF/eclipse/configuration/config.ini 設定:
osgi.bundles=bundle1@start, bundle2@start, ... bundleN@start
可自動啟動所有 Bundle,但需逐一配置 @start,仍嫌繁瑣。
選擇一個 Bundle 在 config.ini 設為自動啟動,再在其 Activator 中啟動所有其他 Bundle。範例程式碼:
public class OSGiStartingBundleActivator implements BundleActivator {
public static BundleContext bundleContext = null;
public void start(BundleContext context) throws Exception {
bundleContext = context;
// 啟動已安裝但未啟動的 Bundle
Bundle[] allBundles = context.getBundles();
for (int i = 0; i < allBundles.length; i++) {
int currState = allBundles[i].getState();
if (Bundle.ACTIVE != currState && Bundle.RESOLVED == currState) {
System.out.println("starting bundle : " + allBundles[i].getSymbolicName());
try {
allBundles[i].start();
} catch (BundleException e) {
e.printStackTrace();
}
}
}
}
public void stop(BundleContext context) throws Exception { }
}
此法僅需配置一個啟動器 Bundle,程式碼自動掃描並啟動所有 RESOLVED 狀態的 Bundle,彈性最高且易維護。