项目结构
引入依赖
apply plugin:'java'repositories{ maven{ url 'http://maven.aliyun.com/nexus/content/groups/public/' }}dependencies{ compile group: 'org.springframework.boot', name: 'spring-boot-starter-web', version: '1.4.2.RELEASE' compile group: 'org.springframework.boot', name: 'spring-boot-starter-test', version: '1.4.2.RELEASE' compile group: 'io.springfox', name: 'springfox-swagger2', version: '2.7.0' compile group: 'io.springfox', name: 'springfox-swagger-ui', version: '2.7.0'}
用户类
public class User { private Long id; private String name; private Integer age;
控制器类
@RestController@RequestMapping(value = "/users")public class UserController { static Mapusers = Collections.synchronizedMap(new HashMap ()); @ApiOperation(value = "获取用户列表", notes = "") @RequestMapping(value = "/", method = RequestMethod.GET) public List getUserList() { // 获取列表 List list = new ArrayList (users.values()); return list; } @ApiOperation(value = "创建用户", notes = "根据User对象创建用户") @ApiImplicitParam(name = "user", value = "用户详细实体user", required = true, dataType = "User") @RequestMapping(value = "/", method = RequestMethod.POST) public String postUser(@ModelAttribute User user) { // 添加user users.put(user.getId(), user); return "success"; } @ApiOperation(value = "获取用户详细信息", notes = "根据url的id来获取用户详细信息") @ApiImplicitParam(name = "id", value = "用户ID", required = true, dataType = "Long", paramType = "path") @RequestMapping(value = "/{id}", method = RequestMethod.GET) public User getUesr(@PathVariable Long id) { // 获取单个实体 return users.get(id); } @ApiOperation(value = "更新用户详细信息", notes = "根据url的id来指定更新对象,并根据传过来的user信息来更新用户详细信息") @ApiImplicitParams({ @ApiImplicitParam(name = "id", value = "用户ID", required = true, dataType = "Long", paramType = "path"), @ApiImplicitParam(name = "user", value = "用户详细实体user", required = true, dataType = "User") }) @RequestMapping(value = "/{id}", method = RequestMethod.PUT) public String putUser(@PathVariable Long id, @ModelAttribute User user) { // 修改实体 User item = users.get(id); item.setName(user.getName()); item.setAge(user.getAge()); users.put(id, item); return "success"; } @ApiOperation(value = "删除用户", notes = "根据url的id来指定删除对象") @ApiImplicitParam(name = "id", value = "用户ID", required = true, dataType = "Long", paramType = "path") @RequestMapping(value = "/{id}", method = RequestMethod.DELETE) public String deleteUser(@PathVariable Long id) { // 删除单个实体 users.remove(id); return "success"; }}
Swagger2类
@Configuration@EnableSwagger2public class Swagger2 { @Bean public Docket createRestApi() { return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo()).select() .apis(RequestHandlerSelectors.basePackage("com.kimisme.web")).paths(PathSelectors.any()).build(); } private ApiInfo apiInfo() { return new ApiInfoBuilder().title("Spring Boot中使用Swagger2构建RESTful APIs") .description("在网页中输入http://localhost:8080/swagger-ui.html会看到惊喜") .termsOfServiceUrl("http://kimisme.com/").contact("绝影").version("1.0").build(); }}
测试类
import static org.hamcrest.Matchers.equalTo;import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;@RunWith(SpringJUnit4ClassRunner.class)@SpringApplicationConfiguration(classes = MockServletContext.class)@WebAppConfigurationpublic class ApplicationTests { private MockMvc mvc; @Before public void setUp() { mvc = MockMvcBuilders.standaloneSetup(new HelloController(), new UserController()).build(); } @Test public void getHello() throws Exception { mvc.perform(MockMvcRequestBuilders.get("/hello").accept(MediaType.APPLICATION_JSON)).andExpect(status().isOk()) .andExpect(content().string(equalTo("Hello World"))); } @Test public void testUserController() throws Exception { RequestBuilder request = null; // 1.0 get获取user列表,返回空 request = get("/users/"); mvc.perform(request).andExpect(status().isOk()).andExpect(content().string(equalTo("[]"))); // 2.0 post添加一个user request = post("/users/").param("id", "1").param("name", "Tony").param("age", "20"); mvc.perform(request) // .andDo(MockMvcResultHandlers.print())//打印本次请求详情 .andExpect(content().string(equalTo("success"))); // 3.0 get查询列表,返回刚插入的数据 request = get("/users/"); mvc.perform(request).andExpect(status().isOk()) .andExpect(content().string(equalTo("[{\"id\":1,\"name\":\"Tony\",\"age\":20}]"))); // 4.0 put修改id为1的user request = put("/users/1").param("name", "Lily").param("age", "18"); mvc.perform(request).andExpect(content().string(equalTo("success"))); // 5.0 get获取id为1的user request = get("/users/1"); mvc.perform(request).andExpect(content().string(equalTo("{\"id\":1,\"name\":\"Lily\",\"age\":18}"))); // 6.0 del删除id为1的user request = delete("/users/1"); mvc.perform(request).andExpect(content().string(equalTo("success"))); // 7、get获取user列表,返回空 request = get("/users/"); mvc.perform(request).andExpect(status().isOk()).andExpect(content().string(equalTo("[]"))); }}
测试
在浏览器输入http://localhost:8080/swagger-ui.html