Spring4.x学习笔记 ——Spring整合Web项目的原理及步骤

一、spring整合web项目原理

1、问题
  • 按传统方式每当访问一个action,都需new ClassPathXmlApplicationContext(path);此时,都要解析一遍spring的核心配置.xml文件,效率太低
2、解决方案
  • 把加载核心配置和创建对象的过程都交给服务器处理,在服务器启动时解析
3、实现原理
  • ServletContext对象
  • 监听器
4、步骤
  • 服务器启动时,为每一个项目创建一个ServletContext对象
  • 监听器监听ServletContext对象的创建,监听到后
    • 加载spring配置文件,创建对象
    • 把创建的对象放到ServletContext域中 setAttribute()
    • 当获取对象时,用getAttribute()

二、具体步骤

1、引入web整合的jar包
  • spring-web
2、在web.xml配置spring核心配置的位置及注册监听器
 <!-- 指定spring配置文件的位置 -->
  <context-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:aop.xml</param-value>
  </context-param>
  <!-- 配置监听器 -->
  <listener>
      <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>

猜你喜欢

转载自blog.csdn.net/qq_37969433/article/details/80033190