Spring集成Web环境

1.Spring继承junit

原始问题:在测试类中,每个测试方法都有以下两行代码:

1
2
ApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml");
UserDao userDao = (UserDao) app.getBean("UserDao"); //userDao为一个例子

这两行代码的作用是获取容器,如果不写的话直接会提示空指针异常,所以又不能轻易删掉。

但是,一个项目下会有多个测试类,每个测试类都需要执行这两行代码,这就存在大量重复工作,因此,可以用Spring继承junit,让SpringJunit来创建Spring容器

集成步骤

  • 导入Spring集成junit的坐标
  • 使用@Runwith注解替换原来的运行期
  • 使用@ContextConfiguration指定配置文件或配置类
  • 使用@Autowired注入需要测试的对象
  • 创建测试方法进行测试

首先导入Springjunit坐标

1
2
3
4
5
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.0.5</version>
</dependency>

然后添加注解:

7aInHg.png

2.Spring继承web

一个web包下会有多个servlet业务,每个业务使用前都需要写这两行代码来获取app对象,这就存在大量重复工作,因此,可以用Spring继承web,让SpringWeb来创建Spring容器

但是,如何让多个servlet都只共享一个spring创建呢,

当然,我们可以将创建spring的两行代码修饰为静态,

不过,现在我们采用Lisenter(监听器)的技术。

我们可以创建一个监听器类,里边进行spring的创建,每次加载项目时该类就被执行了,spring最开始就被创建,之后的servlet都只共享这一个spring了。

可以手动创造,但spring提供了相关方法。

配置文件:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
首先,导入Springweb坐标:
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>5.0.5</version>
</dependency>
然后,配置监听器:
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>

可以使用全局初始化参数优化从ServletContext中获取app的步骤,避免因名称错误而获取不到。
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>

Spring集成web环境步骤

1.配置ContextLoaderListener监听器

2.使用WebApplicationContextUtils获得应用上下文。

3.具体方法:

  • 在Web项目中,可以使用ServletContextListener监听Web应用的启动,我们可以在Web应用启动时,就加载Spring的配置文件,创建应用上下文对象ApplicationContext,再将其存储到最大域ServletContext域中,这样就可以在任意位置从域中获得应用上下文ApplicationContext对象。

web中使用:

1
2
3
4
5
6
Servlet中的doGet方法:

ServletContext servletContext = this.getServletContext();
ServletContext app = WebApplicationContextUtils.getWebApplicationContext(servletContext);
UserService userService = app.getBean(UserService.class);
userService.save();