Spring整合web项目

Spring整合web项目原理

1 加载核心配置文件

(1)new对象,ClassPathXMLApplication,效率很低

2 实现思想:把加载配置文件和创建对象过程,在服务器启动的时候完成

3 实现原理

(1)ServletContext对象

(2)监听器

(2)具体使用

  • 在服务器启动的时候,为每个项目创建一个ServletContext对象
  • 在ServletContext对象创建的时候,使用监听器可以具体到ServletContext对象在什么时候创建
  • 使用监听器监听到ServletContext对象创建到时候
  • 加载Spring配置文件,把配置文件配置对象创建
  • 把创建出来的对象放到ServletContext域对象里面(setAttribute方法)
  • 获取对象的时候,到ServiceContext域得到(getAttribute方法)

Spring整合web项目演示

  1. 演示问题

    (1)action调用service,service调用dao:每次访问action对象都要加载一次Spring配置文件然后再操作

  2. 解决方案

    (1)在服务器启动的时候,创建对象加载配置文件

    (2)底层使用监听器,ServletContext对象

  3. 在spring里面不需要我们自己写代码实现,帮封装

    (1)封装了一个监听器,只需要配置监听器就可以

    (2)配置监听器之前需要导入spring-web的jar包

    配置监听器:在web.xml文件中写

    <listener>
    <listenerclass>org.springfamework.web.context.ContextLoaderListener</listener-class>
    </listener>
    

    (3)指定监听器作用的位置,因为默认在WEB-INF下找application.xml文件,指定文件的方法:

<context-param>
    <!-- 在监听器源代码中找到监听器的父类,父类中有一个常量,contextConfigLocation-->
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:(有包加包/包名)bean1.xml</param-value>
</context-param>
posted @ 2019-11-03 19:11  jirath  阅读(122)  评论(0编辑  收藏  举报