一、使用Servlet进行集成测试
1.直接在Servlet 加载Spring 配置文件
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
HelloService helloService = (HelloService) applicationContext.getBean("helloService");
helloService.sayHello();
问题: 每次请求都会加载Spring环境,初始化所有Bean ,性能问题 !!!
解决方案一: 将代码放入Servlet init 中 , 无法保证所有Servlet都能使用 ApplicationContext
解决方案二: ServletContext,在tomcat启动时, 加载Spring配置文件,获得对象 ,放入ServletContext
* ServletContextListener
2.导入spring-web.jar
保存 ContextLoaderListener 完成在Servlet初始化阶段,加载Spring配置文件,将工厂对象放入 ServletContext
3.配置web.xml
org.springframework.web.context.ContextLoaderListener
* 默认读取 WEB-INF/applicationContext.xml
配置全局参数 contextConfigLocation 指定 配置文件位置
contextConfigLocation
classpath:applicationContext.xml
4.修改Servlet代码
从ServletContext中获得 Spring工厂
第一种:
WebApplicationContext applicationContext = (WebApplicationContext) getServletContext().getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
第二种:
WebApplicationContext applicationContext = WebApplicationContextUtils.getWebApplicationContext(getServletContext());
**********************************************************************************完整代码*********************************************************************************
1)编写service(bean):
public class HelloService {
public void sayHello() {
System.out.println("hello,Spring web");
}
}
2)注册bean:
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
3)配置web.xml文件
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
org.springframework.web.context.ContextLoaderListener
contextConfigLocation
classpath:applicationContext.xml
HelloServlet
cn.itcast.servlet.HelloServlet
HelloServlet
/hello
index.jsp
4)编写servlet(测试)
public class HelloServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
WebApplicationContext applicationContext = WebApplicationContextUtils.getWebApplicationContext(getServletContext());
HelloService helloService = (HelloService) applicationContext.getBean("helloService");
helloService.sayHello();
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
二、Spring 整合 junit4 测试
1、 导入spring-test.jar
2、 编写测试用例
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:applicationContext.xml") // 指定配置文件位置
public class HelloServiceTest {
@Autowired
private HelloService helloService; // 注入需要测试对象
@Test
// 测试
public void demo2() {
helloService.sayHello(); // 调用测试方法
}
}