在servlet或者filter或者Listener中使用spring的IOC容器的方法是:
WebApplicationContext webApplicationContext = WebApplicationContextUtils.getWebApplicationContext(request.getSession().getServletContext());
由于spring是注入的對(duì)象放在ServletContext中的,所以可以直接在ServletContext取出WebApplicationContext 對(duì)象:
WebApplicationContext webApplicationContext = (WebApplicationContext) servletContext.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
事實(shí)上WebApplicationContextUtils.getWebApplicationContext方法就是使用上面的代碼實(shí)現(xiàn)的,建議使用上面上面的靜態(tài)方法
注意:在使用webApplicationContext.getBean("ServiceName")的時(shí)候,前面強(qiáng)制轉(zhuǎn)化要使用接口,如果使用實(shí)現(xiàn)類會(huì)報(bào)類型轉(zhuǎn)換錯(cuò)誤。如:
LUserService userService = (LUserService) webApplicationContext.getBean("userService");