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 ...
随机推荐
- excel绝对引用中间添加符号
=F1&"_"&J1 绝对引用 相对引用 按F4 然后复制全部,选择性黏贴,值和数字即可
- NATAPP打穿内网
前一篇博文写了ngrok作为内网穿透工具现在开始开始学习另外一种内 网穿透natapp(他也是基于ngrok的一种高速内网穿透服务)多的介绍就 不说了,开始进入正题. 第一步:先登录natapp官网( ...
- No cache or cacheManager properties have been set. Authorization cache cannot be obtained.
20235 [http-bio-8080-exec-10] INFO o.a.shiro.realm.AuthorizingRealm - No cache or cacheManager prope ...
- ORBSlam with ROS
...相机标定 calibration 基本就是做CV 的常识 ORBSlam源码:
- SSH框架中配置log4j的方法
SSH框架中使用log4j的方便之处 1. 动态的改变记录级别和策略,即修改log4j.properties,不需要重启Web应用,这需要在web.xml中设置一下.2. 把log文件定在 /WEB- ...
- Android-Java-了解编译
在多年以前,计算机早期的运行方式是 01010100 ....., 这种方式的时候,开发人员编写代码是把01010101/01100101/01010111 ..... /来汇编写代码,这种方式特别痛 ...
- boot分区剩余空间不足
Linux boot分区用于存放内核文件以及Linux一些启动配置文件,一般情况下分区大小为500M足够使用,如果出现空间不足的问题可以使用以下方法来解决. 查看已经安装的内核 dpkg --ge ...
- NLayerAppV3--DDD之领域层
回顾:NLayerAppV3是一个使用.net 2.1实现的经典DDD的分层架构的项目. NLayerAppV3是在NLayerAppV2的基础上,使用.net core2.1进行重新构建的:它包含了 ...
- dorado-SplitSpanel控件
1.这是一个界面布局控件 2.分为SideControl边区域和MainControl主区域 3.常用属性 3.1 collapsed:打开页面时,边区域是否显示 3.2 position:边区域占总 ...
- easyui-layout系列之布局(1)
1.Layout布局 通过 $.fn.layout.defaults 重写默认的 defaults. 布局(layout)是有五个区域(北区 north.南区 south.东区 east.西区 wes ...