spring整合(Junit、web)
阅读原文时间:2023年07月08日阅读:1

1、整合Junit

(1)整合前的测试类代码

public class Test {
public static void main(String[] args) {
ApplicationContext applicationContext=new
ClassPathXmlApplicationContext("applicationContext.xml");
AccountService accountService =(AccountService) applicationContext.getBean("accountService");
accountService.transfer("zhai","zhang",10);
}
}

需要先加载配置文件,获得spring容器,然后从容器中获得对象即可调用相应的类中的方法。

(2)整合后的代码:

需要先导入jar包:

基础包:4+1

测试包:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:applicationContext.xml")
public class Test {
@Autowired//与JUnit整合,不需要在spring的xml配置文件中配置扫描
private AccountService accountService;
public static void main(String[] args) {

    ApplicationContext applicationContext=new  
            ClassPathXmlApplicationContext("applicationContext.xml");  
    AccountService accountService =(AccountService) applicationContext.getBean("accountService");  
    accountService.transfer("zhai","zhang",10);  
}  

}

加载配置文件:

@ContextConfiguration(locations = "classpath:applicationContext.xml")

classpath 的作用是告诉我们配置文件的位置是src目录下。

2、整合web

(1)导入jar包:

(2)tomcat启动时加载配置文件的方式:

servlet init(ServletConfig)

filter init(FilterConfig) web.xml注册过滤器自动调用初始化

listener ServletContextListenter ServletContext 对象监听(spring运用的是这个)

spring提供监听器 ContextLoaderListener web.xml

(3)对web.xml文件进行配置(加载配置文件):


http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app\_4\_0.xsd" version="4.0"> contextConfigLocation classpath:applicationContext.xml org.springframework.web.context.ContextLoaderListener

(4)从servletContext作用域获得spring容器

public class TestServlet extends javax.servlet.http.HttpServlet {
protected void doPost(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException {

}

protected void doGet(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException {  
    //获得spring容器,手动从applicationContext作用域获取  
    ApplicationContext applicationContext=  
            (ApplicationContext) this.getServletContext().getAttribute(WebApplicationContext.ROOT\_WEB\_APPLICATION\_CONTEXT\_ATTRIBUTE);  
    //通过工具获取  
    ApplicationContext applicationContext1=  
            WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());  
    AccountService accountService =(AccountService) applicationContext.getBean("accountService");  
    accountService.transfer("zhai","zhang",10);  
}  

}

获取ApplicationContext 的对象有两种方式。

书写一个页面点击后访问servlet:

<%-- Created by IntelliJ IDEA. User: zhai Date: 2020/4/17/0017 Time: 10:17 To change this template use File | Settings | File Templates. --%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
$Title$ 获得spring容器