在OSGi環境中運行(即在OSGi HttpService中註冊)的HttpServlet想要調用某些OSGi服務來完成它的任務似乎很自然。問題是如何在servlet中獲得對這些OSGi服務的引用。如何從OSGi HttpService中註冊的Servlet獲取OSGi服務引用?
一種方法是依賴注入正在註冊到了OSGi HttpService的像這樣的HttpServlet實例:
MyServlet servlet = new MyServlet();
servlet.setFooService(fooService);
httpService.registerServlet("/myservlet", servlet, initparams, context);
我不知道這是否是因爲在非OSGi環境的有效途徑Servlet生命週期由Web容器管理,因此服務引用不會被注入到稍後創建的servlet實例中。
當使用PAX Web作爲OSGi HttpService的實現時,還有另一種解決方法。 PAX Web將OSGi BundleContext作爲特殊屬性「osgi-bundlecontext」導出到ServletContext中。隨後的BundleContext可用於獲取必要的服務引用:
public void init(ServletConfig servletConfig) throws ServletException {
ServletContext context = servletConfig.getServletContext()
BundleContext bundleContext =
(BundleContext) context.getAttribute("osgi-bundlecontext");
ServiceReference serviceRef =
bundleContext.getServiceReference("com.foo.FooService")
}
但是這種做法是相當醜陋和領帶你一個具體的實現了OSGi HttpService的的。你知道任何其他(可能更好)的解決方案嗎?
Pax Web Extender白板看起來像是一個很好的註冊servlet的解決方案。謝謝。然而,主要問題是如何從OSGi環境中的servlet中獲取服務引用。 你已經提到了JNDI查找,但它不覺得正確的方式來訪問OSGi服務註冊表。然後你也提到了servlet上下文,但是沒有辦法使用OSGi HttpService接口將對象放入servlet上下文中。如果我錯了,請糾正我。 – 2009-06-17 12:57:27