SpringBoot 集成 Swageer2
添加Maven依赖
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.8.0</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.8.0</version>
</dependency>
添加配置类
package com.erp.server.config; 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.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2; @EnableSwagger2
@Configuration
public class SwaggerConfig { @Bean
public Docket creatRestApi(){
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.erp.server.controller"))
.paths(PathSelectors.any())
.build();
} private ApiInfo apiInfo(){
return new ApiInfoBuilder()
.title("进销存系统")
.description("这里是进销存系统的后台接口文档")
//服务条款网址
.termsOfServiceUrl("http://localhost:8080/swagger-ui.html")
//联系人
.contact(new Contact("wangbo","url地址", "email地址"))
.version("1.0")
.build();
} }
注解使用
@Api
用在请求类上,说明该类的作用。可以标记一个Controller类做为swagger文档资源。
value:url的路径值,在UI界面上也看到,可以不用配置。
String value() default "";
tags:说明该类的作用,可以在UI界面上看到的内容
String[] tags() default {""};
produces:配置返回数据类型,例如application/json,application/xml等
String produces() default "";
consumes:配置请求头,例如application/json,application/xml等
String protocols() default "";
authorizations:高级特性认证时配置
Authorization[] authorizations() default {@Authorization("")};
hidden:默认为false,配置为true将在文档中隐藏
boolean hidden() default false;
@ApiOperation
用在请求的方法上,说明方法的用途、作用
value:说明方法的用途、作用
String value();
notes:方法的备注说明
String notes() default "";
tags:
String[] tags() default {""};
response:返回的对象
Class<?> response() default Void.class;
responseContainer:这些对象是有效的List,Set,Map,其他是无效的
String responseContainer() default "";
responseReference:
String responseReference() default "";
httpMethod:可以配置其中HTTP请求方式
String httpMethod() default "";
nickname:
String nickname() default "";
produces:配置返回数据类型,例如application/json,application/xml等
String produces() default "";
consumes:配置请求头,例如application/json,application/xml等
String consumes() default "";
protocols:
String protocols() default "";
authorizations:高级特性认证时配置
Authorization[] authorizations() default {@Authorization("")};
hidden:默认为false,配置为true将在文档中隐藏
boolean hidden() default false;
responseHeaders:配置响应头
ResponseHeader[] responseHeaders() default {@ResponseHeader(
name = "",
response = Void.class
)};
code:HTTP的状态码,默认200
int code() default 200;
extensions:扩展属性
Extension[] extensions() default {@Extension(
properties = {@ExtensionProperty(
name = "",
value = ""
)}
)};
@ApiImplicitParams
用在请求的方法上,表示一组参数说明,里面通过ApiImplicitParam配置具体参数。
public @interface ApiImplicitParams {
ApiImplicitParam[] value();
}
@ApiImplicitParam
用在请求的方法上,表示单个参数说明;或者用在@ApiImplicitParams注解中,指定一个请求参数的各个方面
name:参数名
String name() default "";
value:参数说明解释
String value() default "";
defaultValue:参数的默认值
String defaultValue() default "";
allowableValues:
String allowableValues() default "";
required:参数是否必传 true | false,默认false
boolean required() default false;
access:
String access() default "";
allowMultiple:
boolean allowMultiple() default false;
dataType:参数类型,默认String,只作为标志说明,不做实际验证,String和Long
String dataType() default "";
dataTypeClass:
Class<?> dataTypeClass() default Void.class;
paramType:查询参数位置
header:请求参数放置于 Header,使用@RequestHeader获取
query:请求参数放置于请求地址后边,使用@RequestParam获取
path:请求参数放置于请求地址路径中,使用@PathVariable获取
body:以流的形式提交参数,仅支持POST
form:以form表单的形式提交参数,仅支持POST
String paramType() default "";
example:
String example() default "";
examples:
Example examples() default @Example({@ExampleProperty(
mediaType = "",
value = ""
)});
type:
String type() default "";
format:
String format() default "";
allowEmptyValue:
boolean allowEmptyValue() default false;
readOnly:
boolean readOnly() default false;
collectionFormat:
String collectionFormat() default "";
@ApiParam
public @interface ApiParam {
String name() default "";
String value() default "";
String defaultValue() default "";
String allowableValues() default "";
boolean required() default false;
String access() default "";
boolean allowMultiple() default false;
boolean hidden() default false;
String example() default "";
Example examples() default @Example({@ExampleProperty(
mediaType = "",
value = ""
)});
String type() default "";
String format() default "";
boolean allowEmptyValue() default false;
boolean readOnly() default false;
String collectionFormat() default "";
}
@ApiModel
一般用在请求参数无法使用@ApiImplicitParam注解进行描述的时候,用于对类进行说明,描述一个Model的信息,表示参数用实体类接收。
public @interface ApiModel {
String value() default "";
String description() default "";
Class<?> parent() default Void.class;
String discriminator() default "";
Class<?>[] subTypes() default {};
String reference() default "";
}
@ApiModelProperty
注解用于方法、字段,表示对model属性的说明或者数据操作更改,配合ApiModel一起使用。
public @interface ApiModelProperty {
String value() default "";
String name() default "";
String allowableValues() default "";
String access() default "";
String notes() default "";
String dataType() default "";
boolean required() default false;
int position() default 0;
boolean hidden() default false;
String example() default "";
boolean readOnly() default false;
String reference() default "";
boolean allowEmptyValue() default false;
}
@ApiResponses
用在请求的方法上,表示一组响应
public @interface ApiResponses {
ApiResponse[] value();
}
@ApiResponse
用在@ApiResponses中,一般用于表达一个错误的响应信息
public @interface ApiResponse {
int code();
String message();
Class<?> response() default Void.class;
String reference() default "";
ResponseHeader[] responseHeaders() default {@ResponseHeader(
name = "",
response = Void.class
)};
String responseContainer() default "";
}
@ApiIgnore
用在Controller类或者接口方法上,表示该类或者接口被忽略,不在接口文档显示
public @interface ApiIgnore {
//简要说明为何忽略此参数/操作
String value() default "";
}
问题
目前了解到的是Swagger不支持直接获取JSONObject和Map类型的参数,这种参数内部字段不可知,文档显示不出来
如果不想封装为一个Model的话可以参考下面的博客实现下,自定义一个注解。
https://blog.csdn.net/cy921107/article/details/82761575 JSONObject
https://blog.csdn.net/hellopeng1/article/details/82227942 Map
示例
package com.erp.server.controller; import com.alibaba.fastjson.JSONObject;
import com.erp.server.model.User;
import com.erp.server.service.TestService;
import com.erp.server.utils.Constants;
import com.erp.server.utils.result.ResultBuilder;
import com.erp.server.utils.result.StatusCode;
import io.swagger.annotations.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore; @Api(tags = {"测试接口类"})
@RestController
@RequestMapping(value = "/api/test")
public class TestController { private static final Logger logger = LoggerFactory.getLogger(TestController.class); @Autowired
private TestService testService;
@ApiIgnore
@ApiOperation(value = "测试Hello", notes = "一个测试的hello接口")
@GetMapping("/hello")
public String hello(){
return "Hello Spring Boot";
} @ApiOperation(value = "查询用户", notes = "根据ID查询用户")
@ApiImplicitParam(name = "id", value = "用户ID", required = true, paramType = "path", dataType = "integer")
@GetMapping("/user/{id}")
public ResultBuilder<User> user(@PathVariable("id")Integer id){
User user = testService.getUserById(id);
return new ResultBuilder<User>(user, StatusCode.SUCCESS);
} @ApiOperation(value = "查询用户", notes = "根据ID和姓名查询用户")
@ApiImplicitParams({
@ApiImplicitParam(name = "token", value = "用户凭证", required = true, paramType = "header", dataType = "String"),
@ApiImplicitParam(name = "id", value = "用户ID", required = true, paramType = "query", dataType = "integer"),
@ApiImplicitParam(name = "name", value = "用户名", required = true, paramType = "query", dataType = "String")
})
@GetMapping("/user/id/name")
public ResultBuilder<User> user1(@RequestHeader("token")String token,
@RequestParam("id")Integer id,
@RequestParam("name")String name){
logger.debug("token:{},id:{},name:{}", token, id, name);
User user = testService.getUserById(id);
return new ResultBuilder<User>(user, StatusCode.SUCCESS);
} @ApiOperation(value = "添加用户", notes = "使用JSON数据添加用户")
@ApiImplicitParam(name = "jsonObject", value = "用户数据", required = true, paramType = "body",
examples = @Example(value = @ExampleProperty(mediaType = "application/json", value = "{'id':'','name':'','age':''}"))
)
@PostMapping("/user/add/")
public ResultBuilder<User> adduser(@RequestBody JSONObject jsonObject){
logger.debug(jsonObject.toJSONString());
Integer id = jsonObject.getInteger("id");
User user = testService.getUserById(id);
return new ResultBuilder<User>(user, StatusCode.SUCCESS);
} @ApiOperation(value = "添加用户", notes = "使用对象数据添加用户")
@ApiImplicitParam(name = "user", value = "用户数据", required = true, paramType = "body", dataType = "User")
@PostMapping("/user/add1/")
public ResultBuilder<User> adduser1(@RequestHeader(Constants.ACCEPT_VERSION)String acceptVersion,
@RequestBody User user){
return new ResultBuilder<User>(null, StatusCode.SUCCESS);
} }
@Api 使用示例
属性注释
@Api 使用在接口类上
tags 说明该类的作用,可以在UI界面上看到的内容
示例代码
@Api(tags = {"版本接口类"})
@RestController
@RequestMapping("/api/version")
public class VersionController {
......
}
界面显示

@ApiOperation 和 @ApiImplicitParam 使用示例
属性注释
@ApiOperation 使用在接口方法上
value 接口名
notes 接口注释米描述
@ApiImplicitParams 表示多个参数的情况,需@ApiImplicitParam配合使用
@ApiImplicitParam 表示单个参数
name 参数
value 参数描述
required 参数是否必须,默认false
dataType 参数类型,这个一般还是别写了,经常写了导致无法使用
paramType 参数位置
header:请求参数放置于 Header,使用@RequestHeader获取
query:请求参数放置于请求地址后边,使用@RequestParam获取
path:请求参数放置于请求地址路径中,使用@PathVariable获取
body:以流的形式提交参数,仅支持POST
form:以form表单的形式提交参数,仅支持POST
示例代码
@ApiOperation(value = "采购单列表", notes = "用于查询采购单列表")
@ApiImplicitParams({
@ApiImplicitParam(name = "pageNum", value = "查询的页码,默认1", required = false, paramType = "query"),
@ApiImplicitParam(name = "pageSize", value = "每页显示条数,默认10", required = false, paramType = "query"),
@ApiImplicitParam(name = "wareId", value = "采购ID", required = false, paramType = "query"),
@ApiImplicitParam(name = "startTime", value = "开始时间,毫秒数", required = false, paramType = "query"),
@ApiImplicitParam(name = "endTime", value = "结束时间,毫秒数", required = false, paramType = "query"),
@ApiImplicitParam(name = "wareStatus", value = "采购单状态。-1:删除,0:正常", required = false, paramType = "query"),
@ApiImplicitParam(name = "wareType", value = "采购类型:0:入库单,1:退货单", required = false, paramType = "query")
})
@GetMapping("/list")
public ResultBuilder getWareHouseList(@RequestHeader(Constants.VERSION_CODE)Integer versionCode,
@RequestHeader(Constants.ACCESS_TOKEN)String token,
@RequestParam(value = "pageNum", required = false)Integer pageNum,
@RequestParam(value = "pageSize", required = false)Integer pageSize,
@RequestParam(value = "wareId", required = false)String wareId,
@RequestParam(value = "startTime", required = false)Long startTime,
@RequestParam(value = "endTime", required = false)Long endTime,
@RequestParam(value = "wareStatus", required = false)Integer wareStatus,
@RequestParam(value = "wareType", required = false)Integer wareType){
return wareHouseService.getWareHouseList(pageNum, pageSize, wareId, startTime, endTime, wareStatus, wareType);
}
界面显示

@ApiModel 和 @ApiModelProperty 使用示例
属性注释
@ApiModel 使用在实体类上
value 实体类名称
description 实体类描述信息
@ApiModelProperty 使用在实体类中字段上
value 字段名
required 字段是否必须,默认false
hide 字段是否隐藏,默认false
example 字段值示例
示例代码
实体类
@ApiModel(value = "软件版本", description = "这里是描述信息")
public class Version {
@ApiModelProperty(value = "版本", required = true, example = "1.0.0")
private String version;
@ApiModelProperty(value = "版本号", required = true)
private Integer versionCode;
@ApiModelProperty(value = "最小版本号", required = true)
private Integer minVersionCode;
@ApiModelProperty(value = "强制更新标志", required = true)
private Integer updateForce;
@ApiModelProperty(value = "更新内容")
private String updateContent;
@ApiModelProperty(value = "更新地址", required = true)
private String updateUrl;
@ApiModelProperty(hidden = true)
private Date createTime;
@ApiModelProperty(hidden = true)
private Date updateTime;
省略set/get
}
接口方法
@ApiOperation(value = "新版本检查", notes = "检查APP是否需要进行版本升级")
@PostMapping("/check")
public ResultBuilder versionCheck(@RequestBody Version version){
。。。
}
界面显示


Models中也会显示这个Model

SpringBoot 集成 Swageer2的更多相关文章
- 【springBoot】springBoot集成redis的key,value序列化的相关问题
使用的是maven工程 springBoot集成redis默认使用的是注解,在官方文档中只需要2步; 1.在pom文件中引入即可 <dependency> <groupId>o ...
- SpringBoot集成security
本文就SpringBoot集成Security的使用步骤做出解释说明.
- springboot集成Actuator
Actuator监控端点,主要用来监控与管理. 原生端点主要分为三大类:应用配置类.度量指标类.操作控制类. 应用配置类:获取应用程序中加载的配置.环境变量.自动化配置报告等与SpringBoot应用 ...
- SpringBoot集成Shiro并用MongoDB做Session存储
之前项目鉴权一直使用的Shiro,那是在Spring MVC里面使用的比较多,而且都是用XML来配置,用Shiro来做权限控制相对比较简单而且成熟,而且我一直都把Shiro的session放在mong ...
- SpringBoot集成redis的key,value序列化的相关问题
使用的是maven工程 springBoot集成redis默认使用的是注解,在官方文档中只需要2步; 1.在pom文件中引入即可 <dependency> <groupId>o ...
- springboot集成mybatis(二)
上篇文章<springboot集成mybatis(一)>介绍了SpringBoot集成MyBatis注解版.本文还是使用上篇中的案例,咱们换个姿势来一遍^_^ 二.MyBatis配置版(X ...
- springboot集成mybatis(一)
MyBatis简介 MyBatis本是apache的一个开源项目iBatis, 2010年这个项目由apache software foundation迁移到了google code,并且改名为MyB ...
- springboot集成redis(mybatis、分布式session)
安装Redis请参考:<CentOS快速安装Redis> 一.springboot集成redis并实现DB与缓存同步 1.添加redis及数据库相关依赖(pom.xml) <depe ...
- SpringBoot集成jsp
一.springBoot集成jsp: 1.修改pom文件 <!--集成jsp所需jar包--> <!--jsp页面使用jstl标签--> <dependency> ...
随机推荐
- 【算法】Attention is all you need
Transformer 最近看了Attention Is All You Need这篇经典论文.论文里有很多地方描述都很模糊,后来是看了参考文献里其他人的源码分析文章才算是打通整个流程.记录一下. T ...
- 如何设置PDF签名文档,PDF签名文档怎么编辑
在工作中我们都会遇到有文件需要签名的时候,如果是在身边就直接拿笔来签名了,那么如果没有在身边又是电子文件需要签名的时候应该怎么办呢,这个时候就应该设置一个电子的签名文档,其他的文件电子文件签名很简单, ...
- JMeter关联的几种方式总结案例
1.接口响应结果,通常为HTML.JSON格式的数据,对于HTML的响应结果的提取,可以通过正则表达式,也可以通过XPath 来提取. 2.对于JSON格式的数据,可以通过正则表达式.JSON Ext ...
- 基于docker实现哨兵集群部署
简单dockerfile文件,用于演示sentinel哨兵故障转移FROM centos:latest MAINTAINER BIXIAOYU RUN groupadd -r redis && ...
- Codeforces 258D Little Elephant and Broken Sorting (看题解) 概率dp
Little Elephant and Broken Sorting 怎么感觉这个状态好难想到啊.. dp[ i ][ j ]表示第 i 个数字比第 j 个数字大的概率.转移好像比较显然. #incl ...
- JS中5种经典继承方式
继承 JS中继承的概念: 通过[某种方式]让一个对象可以访问到另一个对象中的属性和方法,我们把这种方式称之为继承 并不是所谓的xxx extends yyy 为什么要使用继承? 有些对象会有方法(动作 ...
- Kali安装Docker
---恢复内容开始--- 第一周 计划安装好docker 准备 审计thinkphp 框架 先把docker 安装的笔记补上 本来是在unbuntu 安装了一遍 并run 了几个镜像和基本操作 ...
- idea通过mapper快速定位到xml文件
1.点击File找到设置(Settings) 2.点击Plugins下的 Browse respositories 3.在搜索栏搜索mybatis ,选中 Free Mybatis plugin——i ...
- B站资源索引
自从搭建了B站的监控之后,就收集了一堆up主,下面分类整理一下,排名不分先后,内容会持续更新……2019-4-10 19:04:08 一.酷玩&装机&开箱 1.AS极客 2.Virtu ...
- [OC] UITableView 与 UItableViewCell 的使用
UITableView //UIViewController里添加一个UITableView @interface ViewController : UIViewController<UITa ...