本文github位置:https://github.com/WillVi/springboot-swagger2-demo

环境准备

  1. JDK版本:1.8
  2. Spring boot版本:1.5.16
  3. Swagger及其Swagger-ui版本:2.6.1(关于swagger-ui版本 每个版本的汉化方式可能有不同)
  4. 默认url:http://localhost:8080/swagger-ui.html

Maven依赖

<!-- swagge2 -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.6.1</version>
</dependency>
<!-- swaggerui用于展示swagger页面 -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.6.1</version>
</dependency>

注意事项:

swagger-ui依赖 有可能会与com.google.guava冲突 提供一个解决办法:

<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.2.2</version>
<!-- 将冲突包移除 -->
<exclusions>
<exclusion>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
</exclusion>
</exclusions>
</dependency>

配置文件

@Configuration
@EnableSwagger2
public class Swagger2Config {
@Bean
public Docket api() {
// 统一设置返回描述
List<ResponseMessage> responseMessages = new ArrayList<>();
responseMessages.add(new ResponseMessageBuilder().code(400).message("请求参数有误").build());
responseMessages.add(new ResponseMessageBuilder().code(401).message("未授权").build());
responseMessages.add(new ResponseMessageBuilder().code(403).message("禁止访问").build());
responseMessages.add(new ResponseMessageBuilder().code(404).message("请求路径不存在").build());
responseMessages.add(new ResponseMessageBuilder().code(500).message("服务器内部错误").responseModel(new ModelRef("string")).build()); return new Docket(DocumentationType.SWAGGER_2)
// 禁用默认返回描述
.useDefaultResponseMessages(false)
// 启用新的返回描述
.globalResponseMessage(RequestMethod.GET, responseMessages)
.globalResponseMessage(RequestMethod.POST, responseMessages)
.globalResponseMessage(RequestMethod.PATCH, responseMessages)
.globalResponseMessage(RequestMethod.PUT, responseMessages)
.globalResponseMessage(RequestMethod.DELETE, responseMessages)
// 设置基本信息
.apiInfo(apiInfo())
.select()
// 设置哪些api被扫描
.apis(RequestHandlerSelectors.basePackage("cn.willvi.springbootswaggerdemo"))
// 设置路径
.paths(PathSelectors.any())
.build();
} /**
* 设置基本信息
* @return
*/
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
// 标题
.title("我的接口文档")
// 描述
.description("这是我的第一个接口文档")
// 版本号
.version("1.0")
// 项目的链接
.termsOfServiceUrl("")
// 作者
.license("willvi")
.licenseUrl("")
.build();
}
}

Swagger注解详解

@Api 设置Controller整体信息

注解位置:Controller类上

/**
* value url路径值(汉化后不起作用) http://xxx/swagger-ui.html#/demo-controller中的 demo-controller即为value
* tags 设置这个值、value的值会被覆盖(汉化后有bug最好不写)
* description 对api资源的描述
* basePath 基本路径可以不配置
* position 如果配置多个Api 想改变显示的顺序位置
* produces 例如, "application/json, application/xml" 页面上的 Response Content Type (响应Content Type)
* consumes 例如, "application/json, application/xml"
* protocols Possible values: http, https, ws, wss.
* authorizations 高级特性认证时配置
* hidden 配置为true 将在文档中隐藏
*/
@Api(value = "Swagger 注解使用",description = "123")

@ApiOperation 设置每个方法(接口)信息

注解位置:方法上

  /**
* value 页面tab右侧值
* tags 如果设置这个值、value的值会被覆盖
* description 对api资源的描述
* basePath 基本路径可以不配置
* position 如果配置多个Api 想改变显示的顺序位置
* produces 例如, "application/json, application/xml"
* consumes 例如, "application/json, application/xml"
* protocols Possible values: http, https, ws, wss.
* authorizations 高级特性认证时配置
* hidden 配置为true 将在文档中隐藏
* response 返回的对象
* responseContainer 这些对象是有效的 "List", "Set" or "Map".,其他无效
* httpMethod "GET", "HEAD", "POST", "PUT", "DELETE", "OPTIONS" and "PATCH"
* code http的状态码 默认 200
* extensions 扩展属性
*/
@ApiOperation(
value = "post",
notes = "这是一个小demo",
produces = "application/json",
response = Person.class
)

@ApiImplicitParams 与 @ApiImplicitParam 设置传入参数信息

注解位置:方法上

注意事项: name必须与参数名相同,不然多出一个参数框

    /**
* @ApiImplicitParam
* 当dataType不是对象时可以使用
*
* paramType:参数放在哪个地方
* name:参数代表的含义
* value:参数名称
* dataType: 参数类型,有String/int,无用
* required : 是否必要
* defaultValue:参数的默认值
*/
@ApiImplicitParams(
@ApiImplicitParam(name = "name",value = "name",paramType ="path", dataType = "String")
)

@ApiResponses 设置返回的一些状态码信息

注解位置:方法上

 /**
* code http的状态码
* message 描述
* response 默认响应类 Void
* reference 参考ApiOperation中配置
* responseHeaders 参考 ResponseHeader 属性配置说明
* responseContainer 参考ApiOperation中配置
*/
@ApiResponses({@ApiResponse(code = 500, message = "服务器内部错误", response = String.class)})

@ApiModel

描述一个Model的信息(这种一般用在post创建的时候,使用@RequestBody这样的场景,请求参数无法使用@ApiImplicitParam注解进行描述的时候

注解位置:实体类上

@ApiModelProperty

描述一个model的属性。

注解位置:实体类每个属性上面

@ApiModelProperty(value = "姓名",name = "name")

@ApiParam

注解位置:方法参数内

 /**
* name 属性名称
* value 属性值
* defaultValue 默认属性值
* allowableValues 可以不配置
* required 是否属性必填
* access 不过多描述
* allowMultiple 默认为false
* hidden 隐藏该属性
* example 举例子
*/
public ResponseEntity<String> placeOrder(
@ApiParam(value = "xxxx", required = true) Person person) {
storeData.add(order);
return ok("");
}

Controler示例

@Api(value = "Swagger 注解使用")

@RestController
@RequestMapping("/") public class DemoController {
@PostMapping("/postHello")
/**
* value url的路径值
* tags 如果设置这个值、value的值会被覆盖
* description 对api资源的描述
* basePath 基本路径可以不配置
* position 如果配置多个Api 想改变显示的顺序位置
* produces 例如, "application/json, application/xml"
* consumes 例如, "application/json, application/xml"
* protocols Possible values: http, https, ws, wss.
* authorizations 高级特性认证时配置
* hidden 配置为true 将在文档中隐藏
* response 返回的对象
* responseContainer 这些对象是有效的 "List", "Set" or "Map".,其他无效
* httpMethod "GET", "HEAD", "POST", "PUT", "DELETE", "OPTIONS" and "PATCH"
* code http的状态码 默认 200
* extensions 扩展属性
*/
@ApiOperation(
value = "post",
notes = "这是一个小demo",
produces = "application/json",
response = Person.class
)
/**
* code http的状态码
* message 描述
* response 默认响应类 Void
* reference 参考ApiOperation中配置
* responseHeaders 参考 ResponseHeader 属性配置说明
* responseContainer 参考ApiOperation中配置
*/
@ApiResponses({@ApiResponse(code = 500, message = "服务器内部错误", response = String.class)})
public ResponseEntity<Person> postHello(@RequestBody Person person){
return ResponseEntity.ok(person);
} @GetMapping("/hello/{name}")
@ApiOperation(
value = "hello world",
notes = "这是一个小demo"
)
/**
* @ApiImplicitParam
* 当dataType不是对象时可以使用
* paramType:参数放在哪个地方
* name:参数代表的含义
* value:参数名称
* dataType: 参数类型,有String/int,无用
* required : 是否必要
* defaultValue:参数的默认值
*/
@ApiImplicitParams(
@ApiImplicitParam(value = "name",paramType ="path", dataType = "String",defaultValue = "world")
)
public String hello(@PathVariable String name){
return "hello " + name;
}
}

Model示例

// 描述一个Model的信息
@ApiModel
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
public class Person {
@ApiModelProperty(value = "姓名",name = "name")
String name;
int age;
}

swagger汉化

  1. 在resources资源下创建 META-INF/resources 文件夹并创建名为swagger-ui.html文件

  2. 复制以下内容:

    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="UTF-8">
    <title>Swagger UI</title>
    <link rel="icon" type="image/png" href="webjars/springfox-swagger-ui/images/favicon-32x32.png" sizes="32x32"/>
    <link rel="icon" type="image/png" href="webjars/springfox-swagger-ui/images/favicon-16x16.png" sizes="16x16"/>
    <link href='webjars/springfox-swagger-ui/css/typography.css' media='screen' rel='stylesheet' type='text/css'/>
    <link href='webjars/springfox-swagger-ui/css/reset.css' media='screen' rel='stylesheet' type='text/css'/>
    <link href='webjars/springfox-swagger-ui/css/screen.css' media='screen' rel='stylesheet' type='text/css'/>
    <link href='webjars/springfox-swagger-ui/css/reset.css' media='print' rel='stylesheet' type='text/css'/>
    <link href='webjars/springfox-swagger-ui/css/print.css' media='print' rel='stylesheet' type='text/css'/> <script src='webjars/springfox-swagger-ui/lib/object-assign-pollyfill.js' type='text/javascript'></script>
    <script src='webjars/springfox-swagger-ui/lib/jquery-1.8.0.min.js' type='text/javascript'></script>
    <script src='webjars/springfox-swagger-ui/lib/jquery.slideto.min.js' type='text/javascript'></script>
    <script src='webjars/springfox-swagger-ui/lib/jquery.wiggle.min.js' type='text/javascript'></script>
    <script src='webjars/springfox-swagger-ui/lib/jquery.ba-bbq.min.js' type='text/javascript'></script>
    <script src='webjars/springfox-swagger-ui/lib/handlebars-4.0.5.js' type='text/javascript'></script>
    <script src='webjars/springfox-swagger-ui/lib/lodash.min.js' type='text/javascript'></script>
    <script src='webjars/springfox-swagger-ui/lib/backbone-min.js' type='text/javascript'></script>
    <script src='webjars/springfox-swagger-ui/swagger-ui.min.js' type='text/javascript'></script>
    <script src='webjars/springfox-swagger-ui/lib/highlight.9.1.0.pack.js' type='text/javascript'></script>
    <script src='webjars/springfox-swagger-ui/lib/highlight.9.1.0.pack_extended.js' type='text/javascript'></script>
    <script src='webjars/springfox-swagger-ui/lib/jsoneditor.min.js' type='text/javascript'></script>
    <script src='webjars/springfox-swagger-ui/lib/marked.js' type='text/javascript'></script>
    <script src='webjars/springfox-swagger-ui/lib/swagger-oauth.js' type='text/javascript'></script> <script src='webjars/springfox-swagger-ui/springfox.js' type='text/javascript'></script>
    <!-- 汉化 -->
    <script src='webjars/springfox-swagger-ui/lang/translator.js' type='text/javascript'></script>
    <script src='webjars/springfox-swagger-ui/lang/zh-cn.js' type='text/javascript'></script>
    </head> <body class="swagger-section">
    <div id='header'>
    <div class="swagger-ui-wrap">
    <a id="logo" href="http://swagger.io"><img class="logo__img" alt="swagger" height="30" width="30" src="webjars/springfox-swagger-ui/images/logo_small.png" /><span class="logo__title">swagger</span></a>
    <form id='api_selector'>
    <div class='input'>
    <select id="select_baseUrl" name="select_baseUrl"/>
    </div>
    <div class='input'><input placeholder="http://example.com/api" id="input_baseUrl" name="baseUrl" type="text"/></div>
    <div id='auth_container'></div>
    <div class='input'><a id="explore" class="header__btn" href="#" data-sw-translate>Explore</a></div>
    </form>
    </div>
    </div> <div id="message-bar" class="swagger-ui-wrap" data-sw-translate>&nbsp;</div>
    <div id="swagger-ui-container" class="swagger-ui-wrap"></div>
    </body>
    </html>
  3. 访问即可

Spring boot整合Swagger的更多相关文章

  1. Spring Boot初识(3)- Spring Boot整合Swagger

    一.本文介绍 如果Web项目是完全前后端分离的话(我认为现在完全前后端分离已经是趋势了)一般前端和后端交互都是通过接口的,对接口入参和出参描述的文档就是Mock文档.随着接口数量的增多和参数的个数增加 ...

  2. Spring Boot整合Swagger报错:"this.condition" is null

    前段时间看到群里有吐槽swagger整合问题,当时没仔细看,总以为是姿势不对. 这两天正好自己升级Spring Boot版本,然后突然出现了这样的一个错误: Caused by: java.lang. ...

  3. Spring Boot整合swagger使用教程

    目录 Swagger的介绍 优点与缺点 添加swagger 1.添加依赖包: 2.配置Swagger: 3.测试 场景: 定义接口组 定义接口 定义接口请求参数 场景一:请求参数是实体类. 场景二:请 ...

  4. Swagger Learing - Spring Boot 整合swagger

    学习了一下swagger. 这是编写的Demo 源码 https://github.com/AmberBar/Learning/tree/master/swagger-learning/swagger ...

  5. spring mvc ,spring boot 整合swagger

    https://blog.csdn.net/qq_35992900/article/details/81274436

  6. Spring Boot初识(4)- Spring Boot整合JWT

    一.本文介绍 上篇文章讲到Spring Boot整合Swagger的时候其实我就在思考关于接口安全的问题了,在这篇文章了我整合了JWT用来保证接口的安全性.我会先简单介绍一下JWT然后在上篇文章的基础 ...

  7. Spring Kafka和Spring Boot整合实现消息发送与消费简单案例

    本文主要分享下Spring Boot和Spring Kafka如何配置整合,实现发送和接收来自Spring Kafka的消息. 先前我已经分享了Kafka的基本介绍与集群环境搭建方法.关于Kafka的 ...

  8. spring boot整合Swagger2

    Swagger 是一个规范和完整的框架,用于生成.描述.调用和可视化RESTful风格的 Web 服务.总体目标是使客户端和文件系统作为服务器以同样的速度来更新.文件的方法,参数和模型紧密集成到服务器 ...

  9. Spring Boot整合JPA、Redis和Swagger2

    好久没有总结了,最近也一直在学习.今天就把spring boot与其它技术的整合做个小总结,主要是jpa.redis和swagger2.公司里有用到这些,整合起来也很简单. 首先,新建一个Spring ...

随机推荐

  1. Swagger与SpringMVC项目整合

    Swagger与SpringMVC项目整合 来源:http://www.2cto.com/kf/201502/376959.html 为了方便的管理项目中API接口,在网上找了好多关于API接口管理的 ...

  2. 64位使用windbg获取Shadow SSDT

    首先选择一个带界面的程序explorer.exe进行附加 kd> !process explorer.exe PROCESS ffff86893dd075c0 SessionId: Cid: 0 ...

  3. 深入redis内部--字典实现

    redis的字典定义和实现在dict.h和dict.c文件中. 1.字典结构 typedef struct dict { dictType *type; //定义了字典需要的函数 void *priv ...

  4. 从源码看 Promise 概念与实现

    Promise 是 JS 异步编程中的重要概念,它较好地解决了异步任务中回调嵌套的问题.在没有引入新的语言机制的前提下,这是如何实现的呢?上手 Promise 时常见若干晦涩的 API 与概念,它们又 ...

  5. C#中使用Log4Net记录日志

    https://www.cnblogs.com/W--Jing/p/8125652.html 实例参考 https://www.cnblogs.com/soundcode/p/4866078.html ...

  6. jQuery的三种$()方式

    http://www.jb51.net/article/21660.htm   $号是jQuery“类”的一个别称,$()构造了一个jQuery对象.所以,“$()”可以叫做jQuery的构造函数(个 ...

  7. Laravel trait的使用

    trait 是在PHP5.4中为了方便代码复用的一种实现方式,但目前我在看的的PHP项目中较少看的有程序员去主动使用这个实现方式,在laravel中有很多 trait 的使用,关于trait 在 la ...

  8. Fask中的路由-模版-静态文件引用 及宏定义与表单

    文档: flask: http://docs.jinkan.org/docs/flask/quickstart.html#redirects-and-errors jinja2 http://docs ...

  9. LeetCode刷题第一天

    1 . 两数之和 给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标. 你可以假设每种输入只会对应一个答案.但是,你不能重复利用 ...

  10. windbg .net 程序的死锁检测 常用方法(个人备份笔记)

    //死锁检测 .load sosex.dll :> !dlk :> !mk -a The mk command displays a call stack of the currently ...