1. 在http://start.spring.io/中生成一個空的項目, 並使用IDEA 打開Open
2. 添加SpringMVC依賴
pom.xml中只有spring-boot-starter(核心模塊,包括自動配置支持、日誌和YAML)和spring-boot-starter-test(測試模塊,包括JUnit、Hamcrest、Mockito)兩個依賴, 現在添加spring-boot-starter-web來集成SpringMVC功能
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
3. HelloWorldController
@RestController
public class HelloWorldController {
@RequestMapping("/hello")
public String index() {
return "Spring Boot Hello World!";
}
}
4. 運行main方法並訪問http://localhost:8080/index
注意:Spring Boot在啓動時會加載groupId.artifactId包下的所有組件,這裏由於在創建項目時沒有添加web依賴,生成的項目在resources下沒有static、templates兩個目錄
5.單元測試:DemoApplicationTests
package com.example.demo;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import static org.hamcrest.Matchers.equalTo;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@RunWith(SpringRunner.class)
@SpringBootTest
public class DemoApplicationTests {
private MockMvc mvc;
@Before
public void setUp() throws Exception {
mvc = MockMvcBuilders.standaloneSetup(new HelloWorldController()).build();
}
@Test
public void testHello() throws Exception {
mvc.perform(MockMvcRequestBuilders.get("/hello").accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(content().string(equalTo("Spring Boot Hello World!")));
}
}
6. Spring MVC 的幾個示例
public class User {
private Long id;
private String name;
private Integer age;
// Getter & Setter
}
@RestController
@RequestMapping("/users")
public class HelloWorldController {
// 創建一個線程安全的Map集合
static Map<Long, User> userMap = Collections.synchronizedMap(new HashMap<>());
@RequestMapping("/hello")
public String index() {
return "Spring Boot Hello World!";
}
@RequestMapping(value = "/", method = RequestMethod.POST)
public String addUser(@ModelAttribute User user){
System.out.println(user.toString());
userMap.put(user.getId(), user);
return "success";
}
// http://localhost:8080/users/?page=1&size=10
@RequestMapping(value = "/", method = RequestMethod.GET)
public List<User> getUserList(@RequestParam(required = false) Integer page, @RequestParam(required = false) Integer size){
System.out.println("page=" + page + " ,size=" + size);
List<User> users = new ArrayList<>(userMap.values());
return users;
}
@RequestMapping(value = "/{id}", method = RequestMethod.GET)
public User getUser(@PathVariable Long id) {
return userMap.get(id);
}
@RequestMapping(value = "/{id}", method = RequestMethod.PUT)
public String updateUser(@PathVariable Long id, @ModelAttribute User user){
User user1 = userMap.get(id);
user1.setName(user.getName());
user1.setAge(user.getAge());
userMap.put(id, user1);
return "success";
}
@RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
public String deleteUser(@PathVariable Long id) {
userMap.remove(id);
return "success";
}
}
DemoApplicationTests
import static org.hamcrest.Matchers.equalTo;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@RunWith(SpringRunner.class)
@SpringBootTest
public class DemoApplicationTests {
private MockMvc mvc;
@Before
public void setUp() throws Exception {
mvc = MockMvcBuilders.standaloneSetup(new HelloWorldController()).build();
}
@Test
public void testHello() throws Exception {
mvc.perform(get("/hello").accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(content().string(equalTo("Spring Boot Hello World!")));
}
@Test
public void testUserApi() throws Exception{
RequestBuilder request = null;
// get 獲取所有用戶列表
request = get("/users/");
mvc.perform(request).andExpect(status().isOk())
.andExpect(content().string(equalTo("[]")));
// post 添加用戶
request = post("/users/")
.param("id", "1")
.param("name", "mengday")
.param("age", "20");
mvc.perform(request).andExpect(content().string(equalTo("success")));
// get get all users
request = get("/users/");
mvc.perform(request).andExpect(content().string(equalTo("[{\"id\":1,\"name\":\"mengday\",\"age\":20}]")));
// put 更新用戶
request = put("/users/1")
.param("name", "mengday")
.param("age", "28");
mvc.perform(request).andExpect(content().string(equalTo("success")));
// 查看某個用戶的信息
request = get("/users/1");
mvc.perform(request).andExpect(content().string(equalTo("{\\\"id\\\":1,\\\"name\\\":\\\"mengday\\\",\\\"age\\\":28}")));
// 刪除用戶信息
request = delete("/users/1");
mvc.perform(request).andExpect(content().string(equalTo("success")));
request = get("/users/");
mvc.perform(request).andExpect(status().isOk()).andExpect(content().string(equalTo("[]")));
}
}
7. 注意
在Application中有一個註解:@SpringBootApplication,在ApplicationTest中有一個註解:@SpringBootTest
單元個測試在測試數據庫的時候如果不想造成垃圾數據,可以開啓事物功能,可以在方法或者類頭部添加@Transactional註解即可。
這樣測試完數據就會回滾了,不會造成垃圾數據。如果你想關閉回滾,只要加上@Rollback(false)註解即可。@Rollback表示事務執行完回滾,支持傳入一個參數value,默認true即回滾,false不回滾。
如果你使用的數據庫是Mysql,有時候會發現加了註解@Transactional 也不會回滾,那麼你就要查看一下你的默認引擎是不是InnoDB,如果不是就要改成InnoDB。
ALTER TABLE user ENGINE=INNODB;
原文鏈接:https://blog.csdn.net/vbirdbest/article/details/79604139