Spring整合Servlet

在servlet里面创建工厂、然后获取实例对象

    //创建工厂
    ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
    
    //获取实例对象
    
    UserService userService = (UserService) context.getBean("us");
    
    userService.save();

初步整合暴露的问题

1. 重复创建工厂。

2. 工厂创建的时机有点晚--- 提前创建 ---提前到项目发布----> 用listener去监听项目的发布。(有8个监听器) --- ServletContextListener

整合Servlet

只要项目一发布,就立即创建工厂,那么我们必须的抓住项目发布的这个契机。 以前在servlet阶段,学过一种东西 监听器  , 可以监听作用域对象的创建与销毁 , SerlvetContext, 这是最大的作用域,全局只有一个对象。 我们都能想到这个点子上, spring框架肯定能够想得到。

在web.xml 中配置 监听器 并且配置param 指定spring配置文件所在

<!-- 这里仅仅是声明了一个监听器,只要servletContext创建了就执行监听器里面的方法。 在方法里面要解析xml文件,然后完成工厂的创建工作。 -->
  <listener>
      <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  
  <!-- 指定了xml的位置在哪里 -->
  <context-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:applicationContext.xml</param-value>
  </context-param>

通过工具类获取之前创建好的工厂

ApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(getServletContext());
UserService userService = (UserService) context.getBean("us");
userService.save();

 

posted @ 2017-12-04 20:18  Dear丶配角  阅读(1862)  评论(0编辑  收藏  举报