本文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. Ubuntu系统Apache Maven安装

    操作系统:Linux x64 / Ubuntu 14.04 Apache Maven版本:3.3.9 建议预先搭建Java开发环境:详见上一篇<Linux Ubuntu系统下Java开发环境搭建 ...

  2. 转:详解PV、UV、VV、IP及其关系与计算

    一.什么是PV? PV即Page View,网站浏览量,指页面浏览的次数,用以衡量网站用户访问的网页数量.用户每次打开一个页面便记录1次PV,多次打开同一页面则浏览量累计.一般来说,PV与来访者的数量 ...

  3. [转]Getting started with ASP.NET Web API OData in 3 simple steps

    本文转自:https://blogs.msdn.microsoft.com/webdev/2013/01/29/getting-started-with-asp-net-web-api-odata-i ...

  4. C#可选参数、命名参数、参数数组

    学习了C#4.0的新特性:可选参数.命名参数.参数数组. 1.可选参数,是指给方法的特定参数指定默认值,在调用方法时可以省略掉这些参数. 但要注意: (1)可选参数不能为参数列表的第1个参数,必须位于 ...

  5. jQuery 判断元素上是否绑定了事件

    我研究了一下之后发现,jQuery都将事件缓存起来了,其实也是为了防止内存溢出以及页面unload的时候的速度,也包括多函数触发,方便管理等诸多好处,具体可以参考此文. jQuery会在window. ...

  6. [linux] C语言Linux系统编程进程基本概念

    1.如果说文件是unix系统最重要的抽象概念,那么进程仅次于文件.进程是执行中的目标代码:活动的.生存的.运行的程序. 除了目标代码进程还包含数据.资源.状态以及虚拟化的计算机. 2.进程体系: 每一 ...

  7. 添加FB登陆时,需要curl扩展

    安装curl扩展遇到一个傻逼问题 [root@xxx openssl]# /usr/local/php/bin/phpizeCannot find config.m4.Make sure that y ...

  8. 【转】Oracle SQL Developer 连接 Mysql 等数据库

    原文地址:http://blog.163.com/cuixiao_yan/blog/static/319232442009102882651869/ Oracle SQL Developer 个人感觉 ...

  9. 最简单应用的时间日期选择插件---My97DatePicker

    最简单的应用:http://www.my97.net/dp/demo/resource/2.1.asp

  10. spring 与 springmvc 的区别和定义

    前言:(内附 spring 下载地址,可以选择需要的版本,给有需要的朋友)补充一下基础知识,spring 的定义和 springmvc 的定义,来源于百度百科. spring 源码下载地址 https ...