0
点赞
收藏
分享

微信扫一扫

Servlet +Spring-----1


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

 



spring是用监听器或Servlet把IOC容器配置到web容器里 以上两个类会把IOC容器放入Servlet容器内,也就是Application范围内, 假设你没有给他设置存入参数,默认的JSP可以采用以下方式得到IOC容器, 从而通过IOC容器得到受管理bean。 <% WebApplicationContext context = (WebApplicationContext)application .getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE); context.getBean("bean id"); %>



web.xml中的加载顺序为:listener >> filter >> servlet >> spring。其中filter的执行顺序是filter- mapping在web.xml中出现的先后顺序。

加载顺序会影响对spring bean的调用。比如filter 需要用到bean ,但是加载顺序是先加载filter 后加载spring,则filter中初始化操作中的bean为null。所以,如果过滤器中要使用到 bean,可以将spring 的加载改成Listener的方式。

复制代码

<context-param>
   <param-name>contextConfigLocation</param-name>
   <param-value>classpath:applicationContext.xml</param-value>
 </context-param>
 <listener>   
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>   
 </listener>

复制代码

      ContextLoaderListener的作用就是启动Web容器时,自动装配ApplicationContext的配置信息。

       如果在web.xml中不写任何参数配置信息,默认的路径是"/WEB-INF/applicationContext.xml",在WEB-INF目录下创建的xml文件的名称必须是applicationContext.xml。如果是要自定义文件名可以在web.xml里加入contextConfigLocation这个context参数。

复制代码

private static ApplicationContext ctx = null;
  public Object getBean(String name) {
       if (ctx == null) {
              ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(this.servletContext);
       }
       return ctx.getBean(name);
  }

复制代码

在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");

举报

相关推荐

0 条评论