本文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. JavaScript设计模式-2高级类.

    <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title> ...

  2. MySQL的连接方式

    连接MySQL操作是连接进程和MySQL数据库实例进行通信.从开发的角度来说,本质上是进程通信.常用的进程通信方式有管道.命名管道.命名字.TCP/IP套接字.Unix域名套接字.MySQL提供的连接 ...

  3. 解决php中json_decode的异常JSON_ERROR_CTRL_CHAR (json_last_error = 3)

    https://www.cnblogs.com/sanshuiqing/p/6022619.html 该字符中含了ASCII码ETB控制符,即\x17导致json解析失败 (截图中显示ETB是因为用了 ...

  4. redis数据类型(四)list类型

    一.list类型 list是一个链表结构,可以理解为一个每个子元素都是 string 类型的双向链表. 主要功能是push.pop.获取一个范围的所有值等. 操作中key理解为链表的名字. 二.Lis ...

  5. ListView和Adapter

    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools= ...

  6. EntityFramework CodeFirst 学习

    个人学习笔记仅供分享,如有错误还请指出 demo结构:models类库和控制台程序 1.首先在model中建立,ADO.NET 实体数据模型---空模型,然后新建数据实体,并且生成数据库 2.控制台想 ...

  7. Linux进程管理之“四大名捕”

    一.四大名捕 四大名捕,最初出现于温瑞安创作的武侠小说,是朝廷中正义力量诸葛小花的四大徒弟,四人各怀绝技,分别是轻功暗器高手“无情”.内功卓越的高手“铁手”.腿功惊人的“追命”和剑法一流的“冷血”本文 ...

  8. html之内容解析

    首先我们知道了HTML和css用途,那么今天就来看看HTML的一部分功能和用途. 简单的说HTML就是灵活使用标签,标签就相当于一个网页的骨架,有了这个骨架才能使网页更能区域色彩化. 首先来说HTML ...

  9. Java注解拾遗

    注解简介: 注解Annotation是jdk1.5的新增功能,在现在的日常开发中,几乎离不开注解,写篇短文,来做个拾遗. 注解作用: Annotation(注解)的作用是修饰包.类.构造方法.方法.成 ...

  10. sql: postgreSQL sql script

    SELECT * from pg_class c,pg_attribute a,pg_type t where c.relname='BookKindList' and a.attnum>0 a ...