介紹Servlet容器與Context
Servlet容器啟動創(chuàng)建了許多對象,如Servlet,filter,listener,spring等等那么如何使用這些對象呢?
下面介紹在Servlet(或者Filter,或者Listener)中使用spring的IOC容器默認情況下Servlet容器創(chuàng)建spring容器對象,注入到Servlet Context中,Servlet Context對象又是注入到session對象中,session對象又是注入到request對象中,request對象又是注入到Servlet對象中,(其實不是很標準的注入,是傳參數,或者對屬性直接付值)。層層依賴可以得到spring容器對象。
- WebApplicationContext webApplicationContext = WebApplicationContextUtils.
getWebApplicationContext(request.getSession().getServletContext());
所以可以直接在Servlet Context取出Web Application Context對象:
- WebApplicationContext webApplicationContext = (WebApplicationContext)
servletContext.getAttribute(WebApplicationContext.
ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
事實上Web Application ContextUtils.getWebApplicationContext方法就是使用上面的代碼實現的,建議使用上面上面的靜態(tài)方法
注意:在使用web Application Context.getBean("ServiceName")的時候,前面強制轉化要使用接口,如果使用實現類會報類型轉換錯誤。如:
- LUserService userService = (LUserService)
webApplicationContext.getBean("userService");
【編輯推薦】