栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Spring 集成web环境

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Spring 集成web环境

前文:Spring提供了一个监听器ContextLoaderListener,该监听器内部加载spring配置文件,创建上下文对象,并存储到ServletContext域中,提供了一个客户端工具WebApplicationContextUtils供使用者获得应用上下文对象。就可以使得spring配置文件applicationContet.xml在teomcat中只需要实例化一次,就可以全局调用。避免了每次getBean()都要new一个ApplicatinContext。

结构:

 

1.导入spring-web坐标


      org.springframework
      spring-web
      5.0.5.RELEASE

2.在web资源文件web.xml中配置spring容器的监听器ContextLoaderListener

  
  
    org.springframework.web.context.ContextLoaderListener
  

3.在web.xml中设置全局参数,告诉监听器ContextLoaderListener要加载的配置文件的名称路径

  
  
    contextConfigLocation
    classpath:applicationContext.xml
  

 注意标签的值为类加载路径,classpath:

web.xml:



  
  
    contextConfigLocation
    classpath:applicationContext.xml
  

  
  
    org.springframework.web.context.ContextLoaderListener
  


  UseServlet
  com.web.UseServlet

  
    UseServlet
    /useServlet
  


4.UseServlet

public class UseServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        ServletContext servletContext = this.getServletContext();
        //ApplicationContext  app = (ApplicationContext) servletContext.getAttribute("app");
        ApplicationContext app = WebApplicationContextUtils.getWebApplicationContext(servletContext);
        UseService useService = (UseService) app.getBean("useService");
        useService.save();
    }
}

手动设置监听器是配置文件在tomcat在加载时就创建在ServletContext域中,这个域很大。 

public class ContextLoadListener implements ServletContextListener {
    
    public void contextInitialized(ServletContextEvent servletContextEvent) {
        ApplicationContext app=new ClassPathXmlApplicationContext("");
        ServletContext servletContext = servletContextEvent.getServletContext();
        servletContext.setAttribute("app",app);
        System.out.println("初始化创建完毕...");
    }

    public void contextDestroyed(ServletContextEvent servletContextEvent) {

    }
}
public class UseServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        ServletContext servletContext = this.getServletContext();
        ApplicationContext  app = (ApplicationContext) servletContext.getAttribute("app");
        ApplicationContext app = //WebApplicationContextUtils.getWebApplicationContext(servletContext);
        UseService useService = (UseService) app.getBean("useService");
        useService.save();
    }
}

 

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/827551.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号