架构实战项目心得(十四):spring-boot结合Swagger2构建RESTful API测试体系
一、添加依赖:
1 <dependency> 2 <groupId>io.springfox</groupId> 3 <artifactId>springfox-swagger2</artifactId> 4 <version>2.6.1</version> 5 </dependency> 6 7 <dependency> 8 <groupId>io.springfox</groupId> 9 <artifactId>springfox-swagger-ui</artifactId> 10 <version>2.6.1</version> 11 </dependency>
二、Swagger配置类
1 package cn.laowang; 2 3 import org.springframework.context.annotation.Bean; 4 import org.springframework.context.annotation.Configuration; 5 import springfox.documentation.builders.ApiInfoBuilder; 6 import springfox.documentation.builders.PathSelectors; 7 import springfox.documentation.builders.RequestHandlerSelectors; 8 import springfox.documentation.service.ApiInfo; 9 import springfox.documentation.spi.DocumentationType; 10 import springfox.documentation.spring.web.plugins.Docket; 11 12 /** 13 * @author zh 14 * @ClassName cn.saytime.Swgger2 15 * @Description 16 * @date 2017-07-10 22:12:31 17 */ 18 @Configuration 19 public class Swagger2 { 20 21 @Bean 22 public Docket createRestApi() { 23 return new Docket(DocumentationType.SWAGGER_2) 24 .apiInfo(apiInfo()) 25 .select() 26 .apis(RequestHandlerSelectors.basePackage("cn.saytime.web")) 27 .paths(PathSelectors.any()) 28 .build(); 29 } 30 31 private ApiInfo apiInfo() { 32 return new ApiInfoBuilder() 33 .title("springboot利用swagger构建api文档") 34 .description("简单优雅的restfun风格,http://blog.csdn.net/saytime") 35 .termsOfServiceUrl("http://blog.csdn.net/saytime") 36 .version("1.0") 37 .build(); 38 } 39 }
三、在SpringBoot主启动类上加上@EnableSwagger2
1 package cn.laowang; 2 3 import org.springframework.boot.SpringApplication; 4 import org.springframework.boot.autoconfigure.SpringBootApplication; 5 import springfox.documentation.swagger2.annotations.EnableSwagger2; 6 7 @SpringBootApplication 8 @EnableSwagger2 9 public class SpringbootSwagger2Application { 10 11 public static void main(String[] args) { 12 SpringApplication.run(SpringbootSwagger2Application.class, args); 13 } 14 }
四、在需要进行测试的方法前面加@ApiOperation
1 package cn.laowang.web; 2 3 import cn.saytime.bean.JsonResult; 4 import cn.saytime.bean.User; 5 import io.swagger.annotations.Api; 6 import io.swagger.annotations.ApiImplicitParam; 7 import io.swagger.annotations.ApiImplicitParams; 8 import io.swagger.annotations.ApiOperation; 9 import org.springframework.http.ResponseEntity; 10 import org.springframework.web.bind.annotation.PathVariable; 11 import org.springframework.web.bind.annotation.RequestBody; 12 import org.springframework.web.bind.annotation.RequestMapping; 13 import org.springframework.web.bind.annotation.RequestMethod; 14 import org.springframework.web.bind.annotation.RestController; 15 import springfox.documentation.annotations.ApiIgnore; 16 17 import java.util.ArrayList; 18 import java.util.Collections; 19 import java.util.HashMap; 20 import java.util.List; 21 import java.util.Map; 22 23 /** 24 * @author laowang 25 * @ClassName cn.saytime.web.UserController 26 * @Description 27 */ 28 @RestController 29 public class UserController { 30 31 // 创建线程安全的Map 32 static Map<Integer, User> users = Collections.synchronizedMap(new HashMap<Integer, User>()); 33 34 /** 35 * 根据ID查询用户 36 * @param id 37 * @return 38 */ 39 @ApiOperation(value="获取用户详细信息", notes="根据url的id来获取用户详细信息") 40 @ApiImplicitParam(name = "id", value = "用户ID", required = true, dataType = "Integer", paramType = "path") 41 @RequestMapping(value = "user/{id}", method = RequestMethod.GET) 42 public ResponseEntity<JsonResult> getUserById (@PathVariable(value = "id") Integer id){ 43 JsonResult r = new JsonResult(); 44 try { 45 User user = users.get(id); 46 r.setResult(user); 47 r.setStatus("ok"); 48 } catch (Exception e) { 49 r.setResult(e.getClass().getName() + ":" + e.getMessage()); 50 r.setStatus("error"); 51 e.printStackTrace(); 52 } 53 return ResponseEntity.ok(r); 54 } 55 56 /** 57 * 查询用户列表 58 * @return 59 */ 60 @ApiOperation(value="获取用户列表", notes="获取用户列表") 61 @RequestMapping(value = "users", method = RequestMethod.GET) 62 public ResponseEntity<JsonResult> getUserList (){ 63 JsonResult r = new JsonResult(); 64 try { 65 List<User> userList = new ArrayList<User>(users.values()); 66 r.setResult(userList); 67 r.setStatus("ok"); 68 } catch (Exception e) { 69 r.setResult(e.getClass().getName() + ":" + e.getMessage()); 70 r.setStatus("error"); 71 e.printStackTrace(); 72 } 73 return ResponseEntity.ok(r); 74 } 75 76 /** 77 * 添加用户 78 * @param user 79 * @return 80 */ 81 @ApiOperation(value="创建用户", notes="根据User对象创建用户") 82 @ApiImplicitParam(name = "user", value = "用户详细实体user", required = true, dataType = "User") 83 @RequestMapping(value = "user", method = RequestMethod.POST) 84 public ResponseEntity<JsonResult> add (@RequestBody User user){ 85 JsonResult r = new JsonResult(); 86 try { 87 users.put(user.getId(), user); 88 r.setResult(user.getId()); 89 r.setStatus("ok"); 90 } catch (Exception e) { 91 r.setResult(e.getClass().getName() + ":" + e.getMessage()); 92 r.setStatus("error"); 93 94 e.printStackTrace(); 95 } 96 return ResponseEntity.ok(r); 97 } 98 99 /** 100 * 根据id删除用户 101 * @param id 102 * @return 103 */ 104 @ApiOperation(value="删除用户", notes="根据url的id来指定删除用户") 105 @ApiImplicitParam(name = "id", value = "用户ID", required = true, dataType = "Long", paramType = "path") 106 @RequestMapping(value = "user/{id}", method = RequestMethod.DELETE) 107 public ResponseEntity<JsonResult> delete (@PathVariable(value = "id") Integer id){ 108 JsonResult r = new JsonResult(); 109 try { 110 users.remove(id); 111 r.setResult(id); 112 r.setStatus("ok"); 113 } catch (Exception e) { 114 r.setResult(e.getClass().getName() + ":" + e.getMessage()); 115 r.setStatus("error"); 116 117 e.printStackTrace(); 118 } 119 return ResponseEntity.ok(r); 120 } 121 122 /** 123 * 根据id修改用户信息 124 * @param user 125 * @return 126 */ 127 @ApiOperation(value="更新信息", notes="根据url的id来指定更新用户信息") 128 @ApiImplicitParams({ 129 @ApiImplicitParam(name = "id", value = "用户ID", required = true, dataType = "Long",paramType = "path"), 130 @ApiImplicitParam(name = "user", value = "用户实体user", required = true, dataType = "User") 131 }) 132 @RequestMapping(value = "user/{id}", method = RequestMethod.PUT) 133 public ResponseEntity<JsonResult> update (@PathVariable("id") Integer id, @RequestBody User user){ 134 JsonResult r = new JsonResult(); 135 try { 136 User u = users.get(id); 137 u.setUsername(user.getUsername()); 138 u.setAge(user.getAge()); 139 users.put(id, u); 140 r.setResult(u); 141 r.setStatus("ok"); 142 } catch (Exception e) { 143 r.setResult(e.getClass().getName() + ":" + e.getMessage()); 144 r.setStatus("error"); 145 146 e.printStackTrace(); 147 } 148 return ResponseEntity.ok(r); 149 } 150 151 @ApiIgnore//使用该注解忽略这个API 152 @RequestMapping(value = "/hi", method = RequestMethod.GET) 153 public String jsonTest() { 154 return " hi you!"; 155 } 156 }
五、启动SpringBootApplication主启动类,访问 http://localhost:8080/swagger-ui.html
六、Swagger2注解
Swagger通过注解表明该接口会生成文档,包括接口名、请求方法、参数、返回信息的等等。
- @Api:修饰整个类,描述Controller的作用
- @ApiOperation:描述一个类的一个方法,或者说一个接口
- @ApiParam:单个参数描述
- @ApiModel:用对象来接收参数
- @ApiProperty:用对象接收参数时,描述对象的一个字段
- @ApiResponse:HTTP响应其中1个描述
- @ApiResponses:HTTP响应整体描述
- @ApiIgnore:使用该注解忽略这个API
- @ApiError :发生错误返回的信息
- @ApiImplicitParam:一个请求参数
- @ApiImplicitParams:多个请求参数