将 OSGi 框架启动器添加到 Web 应用程序并不是什么大问题。
您需要在 web.xml 中添加一个监听器来启动框架启动器
<listener>
<listener-class>at.badgateway.StartupListener</listener-class>
</listener>
启动监听器可能看起来像这样
public class StartupListener implements ServletContextListener {
//vars
@Override
public void contextInitialized(ServletContextEvent event) {
// set props
Map<String, String> config = new HashMap<String, String>();
config.put(Constants.FRAMEWORK_STORAGE, "path to cache");
config.put(Constants.FRAMEWORK_STORAGE_CLEAN, "true");
try {
// get framework and start it
FrameworkFactory frameworkFactory = ServiceLoader.load(FrameworkFactory.class).iterator().next();
framework = frameworkFactory.newFramework(config);
framework.start();
// start existing bundles
bundleContext = framework.getBundleContext();
starter = new MyBundleStarter(servletContext, bundleContext);
starter.launch();
} catch (Exception ex)
}
@Override
public void contextDestroyed(ServletContextEvent arg0) {
// stop framework
}
}
注意上面引号中的 MyBundlestarter 类,它是激活包含在你的战争中的所有包的类。 (例如 /WEB-INF/Osgi-Bundles)
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
public class MyBundleStarter{
private BundleContext bundleContext = null;
public void launch() throws Exception {
ArrayList<Bundle> availableBundles= new ArrayList<Bundle>();
//get and open available bundles
for (URL url : getBundlesInWar()) {
Bundle bundle = bundleContext.installBundle(url.getFile(), url.openStream());
availableBundles.add(bundle);
}
//start the bundles
for (Bundle bundle : availableBundles) {
try{
bundle.start();
}catch()
}
private List<URL> getBundlesInWar() throws Exception {
// returns a list of URLs located at destination
}
}
最后但同样重要的是,您必须将 osgi 框架添加到您的项目中。
<dependency>
<groupId>org.apache.felix</groupId>
<artifactId>org.apache.felix.framework</artifactId>
</dependency>
或
<dependency>
<groupId>org.eclipse.osgi</groupId>
<artifactId>org.eclipse.osgi</artifactId>
</dependency>