在Servlet(或者Filter,或者Listener)中使用spring的IOC容器

 在servlet或者filter或者Listener中使用spring的IOC容器的方法是:

WebApplicationContext webApplicationContext = WebApplicationContextUtils.getWebApplicationContext(

                                                                                                                                                   request.getSession().getServletContext());

由於spring是注入的對象放在ServletContext中的,所以可以直接在ServletContext取出WebApplicationContext 對象:

WebApplicationContext webApplicationContext = (WebApplicationContext) servletContext.getAttribute        (WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);

事實上WebApplicationContextUtils.getWebApplicationContext方法就是使用上面的代碼實現的,建議使用上面上面的靜態方法


注意:在使用webApplicationContext.getBean("ServiceName")的時候,前面強制轉化要使用接口,如果使用實現類會報類型轉換錯誤。如:
LUserService userService = (LUserService) webApplicationContext.getBean("userService");

發佈了27 篇原創文章 · 獲贊 0 · 訪問量 5萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章