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文件进行配置(加载配置文件):
(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" %>
手机扫一扫
移动阅读更方便
你可能感兴趣的文章