Spring与Web项目整合的原理

引言:

  在刚开始我们接触IOC时,我们加载并启用SpringIOC是通过如下代码手动加载 applicationContext.xml 文件,new出context对象,完成Bean的创建和属性的注入。

public class TestIOC {

    @Test
    public void testUser() {
        // 1.加载Spring配置文件,创建对象
        ApplicationContext context = new ClassPathXmlApplicationContext("/spring/applicationContext.xml");
        
        // 2.得到配置创建的对象
        Person person = (Person) context.getBean("person");
        
        // 3.调用bean对象中的方法
        person.test1();
    }
}

  注意:这只是测试代码,我们使用 Junit 进行单元测试,如果我们在实际生产过程中,每次创建对象都使用该代码加载配置文件,再创建对象。这种方法当然不可取,太浪费资源。其实,Spring早就帮我们解决了这个问题。

  

Spring和Web项目整合原理:

  1、实现思想:

    把加载配置文件和创建对象的过程,在服务器启动时完成。

  2、实现原理:

    (1)ServletContext对象

    (2)监听器

  3、具体使用:

    (1)在服务器启动时候,会为每个项目创建一个ServletContext对象

    (2)在ServletContext对象创建的时候,使用监听器(ServletContextListener)可以知道ServletContext对象在什么时候创建

    (3)监听到ServletContext对象创建的时候,即在监听器的 contextInitialized()方法中加载Spring的配置文件,把配置文件配置对象创建

    (4) 把创建出来的对象放到ServletContext域对象里面(setAttribute方法),获取对象的时候,从ServletContext域里得到(getAttribute方法)

Spring整合Web项目演示

  1、演示问题(Struts2项目整合Spring时,不写监听,只通过代码加载Spring配置文件)

  (1)action调用service,service调用dao

  

 

  (2)每次访问 Action 的时候,都会重新加载Spring配置文件

  

  

  2、解决方案:

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

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

 

  3、使用Spring框架,不需要我们写代码实现,帮我们进行了封装

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

(2)配置监听器之前做的事:导入Spring整合 web 项目的 jar 包(Maven项目)

 

4、实际操作

(1)pom.xml中引入以下依赖:

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-web</artifactId>
    <version>4.0.2.RELEASE</version>
</dependency>

  (2)web.xml中配置监听器:

<!-- 配置监听器 -->
<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

  (3)web.xml中指定加载Spring配置文件的位置

  注意:如果我们不指定Spring配置文件的位置,容器会自动去 WEB-INF 目录下找 applicationContext.xml 作为默认配置文件。如果找不到,就会报如下错误。

<!-- 指定Spring配置文件的位置 -->
<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:spring/applicationContext.xml</param-value>
</context-param> 

  控制台打印日志:

原文地址:https://www.cnblogs.com/xb1223/p/10167233.html