添加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的更多相关文章

  1. 【springBoot】springBoot集成redis的key,value序列化的相关问题

    使用的是maven工程 springBoot集成redis默认使用的是注解,在官方文档中只需要2步; 1.在pom文件中引入即可 <dependency> <groupId>o ...

  2. SpringBoot集成security

    本文就SpringBoot集成Security的使用步骤做出解释说明.

  3. springboot集成Actuator

    Actuator监控端点,主要用来监控与管理. 原生端点主要分为三大类:应用配置类.度量指标类.操作控制类. 应用配置类:获取应用程序中加载的配置.环境变量.自动化配置报告等与SpringBoot应用 ...

  4. SpringBoot集成Shiro并用MongoDB做Session存储

    之前项目鉴权一直使用的Shiro,那是在Spring MVC里面使用的比较多,而且都是用XML来配置,用Shiro来做权限控制相对比较简单而且成熟,而且我一直都把Shiro的session放在mong ...

  5. SpringBoot集成redis的key,value序列化的相关问题

    使用的是maven工程 springBoot集成redis默认使用的是注解,在官方文档中只需要2步; 1.在pom文件中引入即可 <dependency> <groupId>o ...

  6. springboot集成mybatis(二)

    上篇文章<springboot集成mybatis(一)>介绍了SpringBoot集成MyBatis注解版.本文还是使用上篇中的案例,咱们换个姿势来一遍^_^ 二.MyBatis配置版(X ...

  7. springboot集成mybatis(一)

    MyBatis简介 MyBatis本是apache的一个开源项目iBatis, 2010年这个项目由apache software foundation迁移到了google code,并且改名为MyB ...

  8. springboot集成redis(mybatis、分布式session)

    安装Redis请参考:<CentOS快速安装Redis> 一.springboot集成redis并实现DB与缓存同步 1.添加redis及数据库相关依赖(pom.xml) <depe ...

  9. SpringBoot集成jsp

    一.springBoot集成jsp: 1.修改pom文件 <!--集成jsp所需jar包--> <!--jsp页面使用jstl标签--> <dependency> ...

随机推荐

  1. bzoj 5495

    今年省选题... 表示当时还没学可持久化trie,所以打60分暴力走人... 现在学了可持久化字典树,就可以搞一搞了嘛! 首先看到题目描述,很容易想到首先搞出异或前缀和,然后建起可持久化字典树 然后考 ...

  2. hibernate-第一章-基础

    一,简介 hibernate是一个开源的ORM框架,它对我们的jdbc进行了轻量级的对象封装,它将我们的POJO与数据库表简历映射关系,是一个全自动的ORM框架;hibernate可以自动生成SQL语 ...

  3. python实现JWT

    python实现JWT 一.常见的几种实现认证的方法 1.1basic auth 1.2cookie 1.3token json web token--一种基于token的json格式web认证方法. ...

  4. Lua脚本在redis分布式锁场景的运用

    目录 锁和分布式锁 锁是什么? 为什么需要锁? Java中的锁 分布式锁 redis 如何实现加锁 锁超时 retry redis 如何释放锁 不该释放的锁 通过Lua脚本实现锁释放 用redis做分 ...

  5. 将一个整数M分成N个整数 要求每个都在区间【minV, maxV】之间

    将一个整数M分成N个整数 要求每个都在区间[minV, maxV]之间,怎么分比较快捷???? 说明: N是>=1且<=9的数,分割的数据只要符合[minV, maxV]区间即可,可以是等 ...

  6. setOnTouchListener在小米手机中不走ACTION_UP而是走ACTION_CANCEL

    单点触控: MotionEvent.ACTION_DOWN:手指 初次接触到屏幕 时触发. MotionEvent.ACTION_MOVE:手指 在屏幕上滑动 时触发,会多次触发. MotionEve ...

  7. Win Server 2003 10条小技巧

    微软推出Windows Server 2003已经有一段时间了,但是,由于它是一个面向企业用户的服务器操作系统,所以,没有引起更多个人用户的注意.实际上,简单地改变一下系统的设置,您也可以将Windo ...

  8. android studio gradle 打jar 包 (混淆+第三方库包)

    将依赖的第三方库打包进自己的jar包 1.先将第三方的库包拿到,然后添加jar包到项目的libs. 2.项目的build.gradle脚本添加下面的task: task buildJar(depend ...

  9. 虚拟机上的Ubuntu 文件系统成为只读模式的解决办法

    虚拟机环境的Linux系统由于是虚拟化虚拟出来的主机环境,因此 经常会出现一些操作系统的问题,今天我遇到了一个Ubuntu操作系统文件系统成了只读模式,无法进行系统的操作,由于出问题的主机是我个人搭建 ...

  10. Hibernate HQL ②

    分页查询: - setFirstResult(int firstResult):设定从哪一个对象开始检索,参数 firstResult 表示这个对象在查询结果中的索引位置,索引位置的起始值为零.默认情 ...