Spring Boot中使用Swagger2构建RESTful API文档

转载声明:商业转载请联系作者获得授权,非商业转载请注明出处 © wekri

随着时间推移,不断修改接口实现的时候都必须同步修改接口文档,而文档与代码又处于两个不同的媒介,除非有严格的管理机制,不然很容易导致不一致现象

添加Swagger2依赖

pom.xml中添加swagger2依赖

        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.2.2</version>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.2.2</version>
        </dependency>

创建swagger2配置

package com.mycompany.financial.nirvana.core.swagger;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

/**
 * Created by liuweiguo on 2017/2/13.
 */
@Configuration
@EnableSwagger2
public class Swagger2 {

    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2).groupName("api")
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.mycompany.financial.nirvana.admin.controller"))
                .paths(PathSelectors.any())
                .build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("有鱼小贷联盟商户端接口")//大标题
                .description("有鱼小贷联盟商户端接口")//详细描述
                .termsOfServiceUrl("http://blog.csdn.net/eacter")
                .contact("有鱼团队")//作者
                .version("1.0")//版本
                .build();
    }


    @Bean
    public Docket demoApi() {
        return new Docket(DocumentationType.SWAGGER_2).groupName("demo")//创建多个分组
                .apiInfo(demoApiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.mycompany.financial.nirvana.demo"))
                .paths(PathSelectors.any())
                .build();
    }

    private ApiInfo demoApiInfo() {
        return new ApiInfoBuilder()
                .title("Spring Boot中使用Swagger2构建RESTful APIs")//大标题
                .description("Swagger2 demo")//详细描述
                .termsOfServiceUrl("http://blog.csdn.net/eacter")
                .contact("有鱼团队")//作者
                .version("1.0")//版本
                .license("The Apache License, Version 2.0")
                .licenseUrl("http://www.apache.org/licenses/LICENSE-2.0.html")
                .build();
    }

}

通过@Configuration注解让spring加载配置,@EnableSwagger2启用Swagger2

再通过createRestApi函数创建Docket的Bean之后,apiInfo()用来创建该Api的基本信息(这些基本信息会展现在文档页面中)。select()函数返回一个ApiSelectorBuilder实例用来控制哪些接口暴露给Swagger来展现,本例采用指定扫描的包路径来定义,Swagger会扫描该包下所有Controller定义的API,并产生文档内容(除了被@ApiIgnore指定的请求)。

添加文档内容

package com.mycompany.financial.nirvana.demo.controller;

import com.mycompany.financial.nirvana.demo.bean.User;
import io.swagger.annotations.*;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import java.util.*;

/**
 * Swagger动态文档demo
 * Created by liuweiguo on 2017/2/13.
 */
@Api(value = "Swagger动态文档demo", description = "this is desc", position = 100, protocols = "http")
@RestController
@RequestMapping(value = "/demo/users")
public class SwaggerController {
    static Map<Long, User> users = Collections.synchronizedMap(new HashMap<>());

    @ApiOperation(value = "获取用户列表", notes = "查询用户列表")
    @RequestMapping(value = {""}, method = RequestMethod.GET)
    @ApiResponses({
            @ApiResponse(code = 100, message = "哟吼")
    })
    public List<User> getUserList() {
        return new ArrayList<>(users.values());
    }

    @ApiOperation(value = "创建用户", notes = "根据User对象创建用户")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "用户ID", required = true, dataType = "Long", paramType = "form"),
            @ApiImplicitParam(name = "name", value = "用户名", required = true, dataType = "String", paramType = "form"),
            @ApiImplicitParam(name = "age", value = "年龄", required = true, dataType = "String", paramType = "form"),
            @ApiImplicitParam(name = "ipAddr", value = "ip哟", required = false, dataType = "String", paramType = "form")
    })
    @RequestMapping(value = "", method = RequestMethod.POST)
    public String postUser(@ApiIgnore 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 getUser(@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 = "name", value = "用户名", required = true, dataType = "String", paramType = "form"),
            @ApiImplicitParam(name = "age", value = "年龄", required = true, dataType = "String", paramType = "form")
    })
    @RequestMapping(value = "/{id}", method = RequestMethod.PUT)
    public String putUser(@PathVariable Long id, @ApiIgnore User user) {
        User u = users.get(id);
        u.setName(user.getName());
        u.setAge(user.getAge());
        users.put(id, u);
        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";
    }


    @ApiIgnore //使用这个注解忽略这个接口
    @ApiOperation(value = "不想显示到文档的接口", notes = "不想显示到文档的接口")
    @ApiImplicitParam(name = "id", value = "用户ID", required = true, dataType = "Long", paramType = "form")
    @RequestMapping(value = "/ignoreMe/{id}", method = RequestMethod.DELETE)
    public String ignoreMe(@PathVariable Long id) {
        users.remove(id);
        return "success";
    }
}

常用注解

  • @Api:将Controller标记为Swagger文档资源。

  • @ApiOperation:描述一个类的一个方法,或者说一个接口

  • @ApiImplicitParams :多个参数描述
  • @ApiImplicitParam:单个参数描述

  • @ApiModel:用对象来接收参数

  • @ApiModelProperty:用对象接收参数时,描述对象的一个字段

其它

  • @ApiResponse:HTTP响应其中1个描述
  • @ApiResponses:HTTP响应整体描述

API文档访问与调试

完成上述操作,启动Spring Boot程序,Swagger会默认把所有Controller中的RequestMapping方法都生成API出来。访问:http://localhost:8080/swagger-ui.html就能看到生成的RESTful API的页面。
这里写图片描述

点开具体的API请求,Try it out!

官网Live Demo http://petstore.swagger.io/

文档数据地址

http://127.0.0.1:8080/v2/api-docs

常见问题

访问不到swagger-ui

到GitHub上找到Swagger-ui项目:https://github.com/swagger-api/swagger-ui,将dist下所有内容拷贝到本地项目web项目中, 并修改 index.html,把默认的数据地址换成自己的数据地址

//url = "http://petstore.swagger.io/v2/swagger.json";
url = "http://localhost:8090/v2/api-docs";

demo地址

https://code.csdn.net/Eacter/springboot-samples/tree/master/swagger

参考信息

Swagger-UI官方网站
Spring boot 2.0 – swagger2 整合 swagger-ui.html 打不开问题
github:swagger-ui

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值