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




















