集成Junit
org.springframework
spring-test
5.3.17
junit
junit
4.13.2
test
package com.sjj.service;
import com.sjj.config.SpringConfig;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
// @ContextConfiguration("classpath:appContext.xml") // Spring配置文件方式
@ContextConfiguration(classes = SpringConfig.class) // 注解配置方式
public class UserServiceTest {
/**
* 集成junit测试
*/
@Autowired // 注入需要测试的对象
private UserService userService;
@Test
public void test(){
userService.UserServiceTest(); // 测试UserService的UserServiceTest方法
}
}
集成Web环境
先添加依赖
org.springframework
spring-web
5.3.17
javax.servlet
javax.servlet-api
3.1.0
javax.servlet.jsp
javax.servlet.jsp-api
2.3.3
build标签
study_Spring03
maven-clean-plugin
3.1.0
maven-resources-plugin
3.0.2
maven-compiler-plugin
3.8.0
maven-surefire-plugin
2.22.1
maven-war-plugin
3.2.2
maven-install-plugin
2.5.2
maven-deploy-plugin
2.8.2
编写一个servlet类
package com.sjj.web;
import com.sjj.config.SpringConfig;
import com.sjj.service.UserService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.stereotype.Controller;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@Controller("userServlet")
public class UserServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
ApplicationContext app = new AnnotationConfigApplicationContext(SpringConfig.class);
UserService userService = (UserService) app.getBean("userService");
userService.userServiceTest();
}
}
准备好webapp内容
将项目部署到tomcat