SpringBoot整合Swagger2

手写Api文档的几个痛点:

  1. 文档需要更新的时候,需要再次发送一份给前端,也就是文档更新交流不及时。
  2. 接口返回结果不明确
  3. 不能直接在线测试接口,通常需要使用工具,比如postman
  4. 接口文档太多,不好管理

Swagger也就是为了解决这个问题,当然也不能说Swagger就一定是完美的,当然也有缺点,最明显的就是代码移入性比较强。

其他的不多说,想要了解Swagger的,可以去Swagger官网,可以直接使用Swagger editor编写接口文档,当然我们这里讲解的是SpringBoot整合Swagger2,直接生成接口文档的方式。

一、依赖

  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配置类

其实这个配置类,只要了解具体能配置哪些东西就好了,毕竟这个东西配置一次之后就不用再动了。 特别要注意的是里面配置了api文件也就是controller包的路径,不然生成的文档扫描不到接口。

  1.  
    package cn.saytime;
  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 classSwagger2{
  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.  
    }

用@Configuration注解该类,等价于XML中配置beans;用@Bean标注方法等价于XML中配置bean。

Application.class 加上注解@EnableSwagger2 表示开启Swagger

  1.  
    package cn.saytime;
  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 classSpringbootSwagger2Application{
  10.  
     
  11.  
    public static void main(String[] args) {
  12.  
    SpringApplication.run(SpringbootSwagger2Application. class, args);
  13.  
    }
  14.  
    }

三、Restful 接口

  1.  
    package cn.saytime.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 zh
  25.  
    * @ClassName cn.saytime.web.UserController
  26.  
    * @Description
  27.  
    */
  28.  
    @RestController
  29.  
    public classUserController{
  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.  
    }

Json格式输出类 JsonResult.class

  1.  
    package cn.saytime.bean;
  2.  
     
  3.  
    public class JsonResult{
  4.  
     
  5.  
    private String status = null;
  6.  
     
  7.  
    private Object result = null;
  8.  
     
  9.  
    // Getter Setter
  10.  
    }

实体User.class

  1.  
    package cn.saytime.bean;
  2.  
     
  3.  
    import java.util.Date;
  4.  
     
  5.  
    /**
  6.  
    * @author zh
  7.  
    * @ClassName cn.saytime.bean.User
  8.  
    * @Description
  9.  
    */
  10.  
    public classUser{
  11.  
     
  12.  
    private int id;
  13.  
    private String username;
  14.  
    private int age;
  15.  
    private Date ctm;
  16.  
     
  17.  
    // Getter Setter
  18.  
    }

项目结构:

这里写图片描述

四、Swagger2文档

启动SpringBoot项目,访问 http://localhost:8080/swagger-ui.html

这里写图片描述

具体里面的内容以及接口测试,应该一看就懂了。这里就不一一截图了。

五、Swagger注解

swagger通过注解表明该接口会生成文档,包括接口名、请求方法、参数、返回信息的等等。

  • @Api:修饰整个类,描述Controller的作用
  • @ApiOperation:描述一个类的一个方法,或者说一个接口
  • @ApiParam:单个参数描述
  • @ApiModel:用对象来接收参数
  • @ApiProperty:用对象接收参数时,描述对象的一个字段
  • @ApiResponse:HTTP响应其中1个描述
  • @ApiResponses:HTTP响应整体描述
  • @ApiIgnore:使用该注解忽略这个API
  • @ApiError :发生错误返回的信息
  • @ApiImplicitParam:一个请求参数
  • @ApiImplicitParams:多个请求参数

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值