转载

介绍Servlet容器与Context

Servlet容器启动创建了许多对象,如Servlet,filter,listener,spring等等那么如何使用这些对象呢?

下面介绍在Servlet(或者Filter,或者Listener)中使用spring的IOC容器默认情况下Servlet容器创建spring容器对象,注入到Servlet Context中,Servlet Context对象又是注入到session对象中,session对象又是注入到request对象中,request对象又是注入到Servlet对象中,(其实不是很标准的注入,是传参数,或者对属性直接付值)。层层依赖可以得到spring容器对象。

  1. WebApplicationContext webApplicationContext = WebApplicationContextUtils.
    getWebApplicationContext(request.getSession().getServletContext());  

所以可以直接在Servlet Context取出Web Application Context对象:

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

事实上Web Application ContextUtils.getWebApplicationContext方法就是使用上面的代码实现的,建议使用上面上面的静态方法

注意:在使用web Application Context.getBean("ServiceName")的时候,前面强制转化要使用接口,如果使用实现类会报类型转换错误。如:

  1. LUserService userService = (LUserService) 
    webApplicationContext.getBean("userService"); 

正文到此结束
Loading...