spring boot整合Swagger2
Swagger 是一个规范和完整的框架,用于生成、描述、调用和可视化RESTful风格的 Web 服务。总体目标是使客户端和文件系统作为服务器以同样的速度来更新。文件的方法,参数和模型紧密集成到服务器端的代码,允许API来始终保持同步。Swagger 让部署管理和使用功能强大的API从未如此简单。
1.代码示例
1).在pom.xml文件中引入Swagger2
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.6.1</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.6.1</version>
</dependency>
2).在Application同级目录下添加Swagger2的配置类
package com.example;
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;
@Configuration
@EnableSwagger2
public class Swagger2Config {
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.example"))
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("Spring Boot中使用Swagger2构建RESTful APIs")
.description("spring boot整合swagger2")
.termsOfServiceUrl("www.baidu.com")
.contact("牛头人")
.version("1.0")
.build();
}
}
如上代码所示,通过 @Configuration 注解,让Spring来加载该类配置。再通过 @EnableSwagger2 注解来启用Swagger2。
通过 createRestApi 函数创建 Docket 的Bean之后, apiInfo() 用来创建该Api的基本信息(这些基本信息会展现在文档页面中)。 select() 函数返回一个 ApiSelectorBuilder 实例用来控制哪些接口暴露给Swagger来展现,本例采用指定扫描的包路径来定义,Swagger会扫描该包下所有Controller定义的API,并产生文档内容(除了被 @ApiIgnore 指定的请求)。
3).新建User实体类
package com.example.swagger2;
public class User {
private String id;
private String name;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
4).新建SwaggerDemoController类
package com.example.swagger2;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
@RestController
@RequestMapping(value="/api")
@Api("SwaggerDemoController相关api")
public class SwaggerDemoController {
static Map<String, User> users = Collections.synchronizedMap(new HashMap<String, User>());
@ApiOperation(value="获取用户列表", notes="")
@ApiResponses({
@ApiResponse(code=400,message="请求参数没填好"),
@ApiResponse(code=404,message="请求路径没有或页面跳转路径不对")
})
@RequestMapping(value={""}, method=RequestMethod.GET)
public List<User> getUserList() {
List<User> r = new ArrayList<User>(users.values());
return r;
}
@ApiOperation(value="创建用户", notes="根据User对象创建用户")
@ApiImplicitParam(name = "user", value = "用户详细实体user", required = true, dataType = "User")
@ApiResponses({
@ApiResponse(code=400,message="请求参数没填好"),
@ApiResponse(code=404,message="请求路径没有或页面跳转路径不对")
})
@RequestMapping(value="", method=RequestMethod.POST)
public String postUser(@RequestBody User user) {
users.put(user.getId(), user);
return "success";
}
@ApiOperation(value="获取用户详细信息", notes="根据url的id来获取用户详细信息")
@ApiImplicitParam(name = "id", value = "用户ID",paramType="path", required = true, dataType = "String")
@ApiResponses({
@ApiResponse(code=400,message="请求参数没填好"),
@ApiResponse(code=404,message="请求路径没有或页面跳转路径不对")
})
@RequestMapping(value="/{id}", method=RequestMethod.GET)
public User getUser(@PathVariable String id) {
System.out.println("id="+id);
return users.get(id);
}
@ApiOperation(value="更新用户详细信息", notes="根据url的id来指定更新对象,并根据传过来的user信息来更新用户详细信息")
@ApiImplicitParams({
@ApiImplicitParam(name = "id", value = "用户ID",paramType="path", required = true, dataType = "String"),
@ApiImplicitParam(name = "user", value = "用户详细实体user", required = true, dataType = "User")
})
@ApiResponses({
@ApiResponse(code=400,message="请求参数没填好"),
@ApiResponse(code=404,message="请求路径没有或页面跳转路径不对")
})
@RequestMapping(value="/{id}", method=RequestMethod.PUT)
public String putUser(@PathVariable String id, @RequestBody User user) {
System.out.println("id="+id);
User u = users.get(id);
u.setName(user.getName());
users.put(id, u);
return "success";
}
@ApiOperation(value="删除用户", notes="根据url的id来指定删除对象")
@ApiImplicitParam(name = "id", value = "用户ID",paramType="path", required = true, dataType = "String")
@ApiResponses({
@ApiResponse(code=400,message="请求参数没填好"),
@ApiResponse(code=404,message="请求路径没有或页面跳转路径不对")
})
@RequestMapping(value="/{id}", method=RequestMethod.DELETE)
public String deleteUser(@PathVariable String id) {
System.out.println("id="+id);
users.remove(id);
return "success";
}
}
说明:
@Api:用在类上,说明该类的作用
@ApiOperation:用在方法上,说明方法的作用
@ApiImplicitParams:用在方法上包含一组参数说明
@ApiImplicitParam:用在@ApiImplicitParams注解中,指定一个请求参数的各个方面
paramType:参数放在哪个地方
header-->请求参数的获取:@RequestHeader
query-->请求参数的获取:@RequestParam
path(用于restful接口)-->请求参数的获取:@PathVariable
body(不常用)
form(不常用)
name:参数名
dataType:参数类型
required:参数是否必须传
value:参数的意思
defaultValue:参数的默认值
@ApiResponses:用于表示一组响应
@ApiResponse:用在@ApiResponses中,一般用于表达一个错误的响应信息
code:数字,例如400
message:信息,例如"请求参数没填好"
response:抛出异常的类
@ApiModel:描述一个Model的信息(这种一般用在post创建的时候,使用@RequestBody这样的场景,请求参数无法使用@ApiImplicitParam注解进行描述的时候)
@ApiModelProperty:描述一个model的属性
通过 @ApiOperation 注解来给API增加说明、通过 @ApiImplicitParams 、 @ApiImplicitParam 注解来给参数增加说明。
需要注意的是:

如果ApiImplicitParam中的phone的paramType是query的话,是无法注入到rest路径中的,而且如果是path的话,是不需要配置ApiImplicitParam的,即使配置了,其中的value="用户ID"也不会在swagger-ui展示出来。
具体其他的注解,查看:
https://github.com/swagger-api/swagger-core/wiki/Annotations#apimodel
2.测试:
启动服务,浏览器输入"http://localhost:8080/swagger-ui.html"
GET红框:method=RequestMethod.GET
右边红框:@ApiOperation
parameter红框:@ApiImplicitParams系列注解
response messages红框:@ApiResponses系列注解
输入参数后,点击"try it out!",查看响应内容:

spring boot整合Swagger2的更多相关文章
- Spring Boot 项目学习 (四) Spring Boot整合Swagger2自动生成API文档
0 引言 在做服务端开发的时候,难免会涉及到API 接口文档的编写,可以经历过手写API 文档的过程,就会发现,一个自动生成API文档可以提高多少的效率. 以下列举几个手写API 文档的痛点: 文档需 ...
- 2018 最新 spring boot 整合 swagger2 (swagger2 版本 2.8.0)
好久没上了, 看到又有人回复了. 我就来修改一下. 修改时间 2018年5月16日 这回给你上全新版本. 至发稿时间,所有的包都是新版. 注意: 高版本需要添加 jaxb-api 包, 否则会报错 ...
- spring boot 整合 swagger2
swagger2为了更好的管理api文档接口 swagger构建的api文档如下,清晰,避免了手写api诸多痛点 一,添加依赖 <!--swagger2的官方依赖--> <depen ...
- Spring Boot 整合Swagger2构建API文档
1.pom.xml中引入依赖 <dependency> <groupId>io.springfox</groupId> <artifactId>spri ...
- Spring Boot整合JPA、Redis和Swagger2
好久没有总结了,最近也一直在学习.今天就把spring boot与其它技术的整合做个小总结,主要是jpa.redis和swagger2.公司里有用到这些,整合起来也很简单. 首先,新建一个Spring ...
- Spring Boot初识(3)- Spring Boot整合Swagger
一.本文介绍 如果Web项目是完全前后端分离的话(我认为现在完全前后端分离已经是趋势了)一般前端和后端交互都是通过接口的,对接口入参和出参描述的文档就是Mock文档.随着接口数量的增多和参数的个数增加 ...
- Spring Boot之Swagger2集成
一.Swagger2简单介绍 Swagger2,它可以轻松的整合到Spring Boot中,并与Spring MVC程序配合组织出强大RESTful API文档.它既可以减少我们创建文档的工作量,同时 ...
- Spring Boot 整合 Elasticsearch,实现 function score query 权重分查询
摘要: 原创出处 www.bysocket.com 「泥瓦匠BYSocket 」欢迎转载,保留摘要,谢谢! 『 预见未来最好的方式就是亲手创造未来 – <史蒂夫·乔布斯传> 』 运行环境: ...
- spring boot整合jsp的那些坑(spring boot 学习笔记之三)
Spring Boot 整合 Jsp 步骤: 1.新建一个spring boot项目 2.修改pom文件 <dependency> <groupId>or ...
随机推荐
- Ubuntu 16.04下安装网络流量分析工具 Wireshark
本文链接地址:https://www.linuxidc.com/Linux/2016-08/134526.htm 切勿用商业用途 sudo apt-add-repository ppa:wiresha ...
- Hdu1896 Stones(优先队列) 2017-01-17 13:07 40人阅读 评论(0) 收藏
Stones Time Limit : 5000/3000ms (Java/Other) Memory Limit : 65535/32768K (Java/Other) Total Submis ...
- Android ADB命令基本常用操作
电脑配置好环境变量之后呢,在cmd里面自测一下,是否配置OK: 1.查看目前连接的设备: adb devices 2.使目前连接的设备重启: adb reboot 3.有时候由于设备冲突导致adb出现 ...
- .net core使用NLog记录
首先使用Nugut安装NLog, NLog.Extensions.Logging,using NLog.Web,并且加上配置文件 ”nlog.config“,配置文件内容网上都可以百度的到.这是我自己 ...
- Ruby on Rails 目录结构
目录结构 + app/ #控制器.模型.视图.帮助方法.邮件.静态资源 + bin/ #rails脚本 + config/ #路由.数据库等 + db/ #数据库模式.迁移文件 + lib/ #扩展模 ...
- 遍历 SortedList<string, string> 中的值(可用于datatable转json)
SortedList<string, string> STK = new SortedList<string, string>();STK.Add("1", ...
- 在微信开发中如果WeixinJSBridge.call('closeWindow');关闭窗口无效!
原因是,成功后页面跳转到普通页面.必须在前面加上 parent.WeixinJSBridge.call('closeWindow'); 这样才行.如果是使用了iframe页面,这样也可以关闭网页,回到 ...
- LD算法的C++实现(基于编辑距离的文本比较算法)
算法看这里: http://www.cnblogs.com/grenet/archive/2010/06/01/1748448.html 用数组实现: #include <iostream> ...
- STL在数组算法的使用
find(a:起始位置 , b: 终止位置 , c: 要查找的内容) ------>查找寻找内容的位置 count(a:起始位置 , b: 终止位置 , c: 要查找的内容) -- ...
- Mac OS 10.12 - 安装Homebrew,像Ubuntu里面的apt一样简单地安装和删除软件!
Homebrew — macOS 不可或缺的套件管理器,Homebrew官方网站如此介绍自己!!! 中文官网:https://brew.sh/index_zh-cn.html 一,安装 打开shell ...