可以使用FrameworkFactory API以编程方式启动任何OSGi框架(R4.1或更高版本):
ServiceLoader ffs = ServiceLoader.load(FrameworkFactory.class);
FrameworkFactory ff = ffs.iterator().next();
Map config = new HashMap();
// add some params to config ...
Framework fwk = ff.newFramework(config);
fwk.start();
OSGi框架现在正在运行。由于Framework扩展了Bundle,你可以调用getBundleContext并调用所有正常的API方法来操作bundle,注册服务等。例如
BundleContext bc = fwk.getBundleContext();
bc.installBundle("file:/path/to/bundle.jar");
bc.registerService(MyService.class.getName(), new MyServiceImpl(), null);
// ...
最后你应该等待框架关闭:
fwk.stop();
fwk.waitForStop(0);
重申一下,这种方法适用于任何OSGi框架,包括Equinox和Felix,只需将框架JAR放在类路径上即可。