OSGi(Open Services Gateway Initiative)定義動態模組化的 Java 服務平台,四大核心層級:
Bundle 六大狀態:INSTALLED → RESOLVED → STARTING → ACTIVE / STOPPING → RESOLVED / UNINSTALLED
Equinox 實作 OSGi R4 核心框架與標準服務。Eclipse 3.2 本身即建構於 Equinox 之上,是開發 Bundle 的最佳 IDE。
BundleActivatorexample.service.NameService):
public interface NameService {
boolean checkName(String name);
}
Activator.start()):
public void start(BundleContext context) {
Properties props = new Properties();
props.put("ClassRoom", "ClassOne");
context.registerService(NameService.class.getName(), new NameImpl(), props);
}
static class NameImpl implements NameService {
String[] names = {"Marry","John","David","Rachel","Ross"};
public boolean checkName(String name) {
for (String n : names) if (n.equals(name)) return true;
return false;
}
}
Bundle-Activator: example.osgi.Activator
Export-Package: example.service
Import-Package: org.osgi.framework;version="1.3.0"
Export-Package 讓其他 Bundle 可見服務介面。public void start(BundleContext context) {
ServiceReference[] refs = context.getServiceReferences(
NameService.class.getName(), "(ClassRoom=*)");
if (refs != null) {
NameService svc = (NameService) context.getService(refs[0]);
// 互動式查詢姓名...
context.ungetService(refs[0]);
}
}
java -jar org.eclipse.osgi_3.2.0.jar -consoleosgi> ss # 列出 Bundle 狀態
osgi> install file:exampleClient.jar
osgi> start <bundle_id>
osgi> stop <bundle_id>
osgi> close






OSGi 提供動態模組化、服務導向的企業級應用基礎。Eclipse/Equinox 讓 Bundle 開發、部署、除錯一體化。掌握 BundleActivator、BundleContext、服務註冊/發現、MANIFEST.MF 配置,即可構建可熱插拔的模組化系統。