Spring框架整合WEB解决配置文件加载多次的问题

1. 创建JavaWEB项目,引入Spring的开发包。编写具体的类和方法。
    * 环境搭建好后,启动服务器来测试项目,发送每访问一次都会加载一次配置文件,这样效率会非常非常慢!!

2. 解决上面的问题
    * 将工厂创建好了以后放入到ServletContext域中.使用工厂的时候,从ServletContext中获得.
        * ServletContextListener:用来监听ServletContext对象的创建和销毁的监听器.
        * 当ServletContext对象创建的时候:创建工厂 , 将工厂存入到ServletContext

3. Spring整合Web项目
    * 引入spring-web-4.2.4.RELEASE.jar包
    * 配置监听器
         <!-- 配置Spring的核心监听器: -->配置到web.xml中
         <listener>
            <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
         </listener>
         <context-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:applicationContext.xml</param-value>
         </context-param>
ActionContext一旦被创建,就会创建监听器,然后加载配置文件,只有服务器关闭的时候监听器才会被销毁。
4. 修改servlet的代码
    * 从ServletContext中获得工厂
    * 具体代码如下
        ServletContext servletContext = ServletActionContext.getServletContext();
        // 需要使用WEB的工厂的方式
        WebApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(servletContext);
        CustomerService cs = (CustomerService) context.getBean("customerService");
        cs.save();  
原文地址:https://www.cnblogs.com/wyhluckdog/p/10127955.html