springboot整合swagger-ui

我想回家      2022-04-26     466

关键词:

SpringBoot整合Swagger-ui

  1. 引入依赖
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>2.9.2</version>
</dependency>

<!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger-ui -->
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>2.9.2</version>
</dependency>
  1. 添加配置类
// 启动时加载类
@Configuration
// 启用Swagger API文档
@EnableSwagger2
public class SwaggerConfig {

    @Bean
    public Docket api() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                // 自行修改为自己的包路径
                .apis(RequestHandlerSelectors.basePackage("com.swagger.springbootswagger.controller"))
                .paths(PathSelectors.any())
                .build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("客户管理")
                .description("客户管理中心 API 1.0 操作文档")
                //服务条款网址
                .termsOfServiceUrl("https://www.cnblogs.com/wadmwz/")
                .version("1.0")
                .contact(new Contact("王智家园", "https://www.cnblogs.com/wadmwz/", "15713598138@sina.cn"))
                .build();
    }

}
  1. Swagger常用注解
作用范围 API 使用位置
协议集描述 @Api 用于 Controller 类上
协议描述 @ApiOperation 用在 Controller 的方法上
非对象参数集 @ApiImplicitParams 用在 Controller 的方法上
非对象参数描述 @ApiImplicitParam 用在 @ApiImplicitParams 的方法里边
响应集 @ApiResponses 用在 Controller 的方法上
响应信息参数 @ApiResponse 用在 @ApiResponses 里边
描述返回对象的意义 @ApiModel 用在返回对象类上
对象属性 @ApiModelProperty 用在出入参数对象的字段上
@Api的使用

API作用在Controller,作为swagger文档资源,该注解将一个controller标注为一个Swagger资源(API). 在默认情况下,Swagger-Core 只会扫描解析具有 @Api 注解的类,而会自动忽略其他类别资源(JAX-RS endpoints、Servlets 等)的注解。

@Api(value = "消息",description = "消息操作 API", position = 100, protocols = "http")
@RestController
@RequestMapping("message")
public class MessageController {
}

启动项目,访问http://localhost:8080/swagger-ui.html#/message-controller 就可以看到效果,自动将MessageController内的方法都添加映射,并标明了每种方法的请求方式

@ApiOperation 的使用

ApiOperation 定义在方法上,描述方法名、方法解释、返回信息、标记等信息。

@ApiOperation(
        value = "消息列表",
        notes = "完整的消息内容列表",
        produces = "application/json, application/xml",
        consumes = "application/json, application/xml",
        response = List.class
)
@GetMapping(value = "messages")
public List<Message> list() {
    List<Message> messages = this.messageRepository.findAll();
    return messages;
}
属性名称 备注
value url 的路径值
tags 如果设置这个值,value 的值会被覆盖
description 对 API 资源的描述
produces For example, "application/json, application/xml"
consumes For example, "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 扩展属性
@ApiImplicitParams 和 @ApiImplicitParam 的使用

@ApiImplicitParams 用于描述方法的返回信息,和 @ApiImplicitParam 注解配合使用;@ApiImplicitParam 用来描述具体某一个参数的信息,包括参数的名称、类型、限制等信息。

@ApiOperation(
        value = "添加信息",
        notes = "根据传递的参数创建信息"
)
@ApiImplicitParams({
        @ApiImplicitParam(name = "id", value = "消息ID", required = true, dataType = "Long", paramType = "query"),
        @ApiImplicitParam(name = "text", value = "消息正文", required = true, dataType = "String", paramType = "query"),
        @ApiImplicitParam(name = "summary", value = "摘要", required = false, dataType = "String", paramType = "query"),

})
@PostMapping(value = "message")
public Message create(Message message) {
    message = this.messageRepository.save(message);
    return message;
}
属性名称 备注
name 接收参数名
value 接收参数的意义描述
required 参数是否必填值为 true 或者 false
dataType 参数的数据类型只作为标志说明,并没有实际验证
paramType 查询参数类型,其值:
path 以地址的形式提交数据
query 直接跟参数完成自动映射赋
body 以流的形式提交,仅支持 POST
header 参数在 request headers 里边提交
form 以 form 表单的形式提交 仅支持 POST
@ApiResponses 和 @ApiResponse 的使用

@ApiResponses 主要封装方法的返回信息和 @ApiResponse 配置起来使用,@ApiResponse 定义返回的具体信息包括返回码、返回信息等。

@ApiOperation(value = "修改信息", notes = "根据参数修改信息")
@ApiResponses({
        @ApiResponse(code = 100, message = "请求信息有误"),
        @ApiResponse(code = 101, message = "未授权"),
        @ApiResponse(code = 103, message = "禁止访问"),
        @ApiResponse(code = 104, message = "请求路径不存在"),
        @ApiResponse(code = 200, message = "服务器内部错误"),
})
@PutMapping(value = "message")
public Message modify(Message message) {
    Message messageResult=this.messageRepository.update(message);
    return messageResult;
}
属性名称 备注
code http 的状态码
message 描述
response 默认响应类 Void
reference 参考
responseHeaders 封装返回信息
responseContainer 字符串
@ApiModel 和 @ApiModelProperty 的使用

在实际的项目中我们常常会封装一个对象作为返回值,@ApiModel 就是负责描述对象的信息,@ApiModelProperty 负责描述对象中属性的相关内容。

@ApiModel(description = "响应对象")
public class BaseResult<T> {

    private static final int SUCCESS_CODE = 0;
    private static final String SUCCESS_MESSAGE = "成功";

    @ApiModelProperty(value = "响应码", name = "code", required = true, example = "" + SUCCESS_CODE)
    private int code;

    @ApiModelProperty(value = "响应消息", name = "msg", required = true, example = SUCCESS_MESSAGE)
    private String msg;

    @ApiModelProperty(value = "响应数据", name = "data")
    private T data;

    private BaseResult(int code, String msg, T data) {
        this.code = code;
        this.msg = msg;
        this.data = data;
    }

    private BaseResult() {
        this(SUCCESS_CODE, SUCCESS_MESSAGE);
    }

    private BaseResult(int code, String msg) {
        this(code, msg, null);
    }

    private BaseResult(T data) {
        this(SUCCESS_CODE, SUCCESS_MESSAGE, data);
    }

    public static <T> BaseResult<T> success() {
        return new BaseResult<>();
    }

    public static <T> BaseResult<T> successWithData(T data) {
        return new BaseResult<>(data);
    }

    public static <T> BaseResult<T> failWithCodeAndMsg(int code, String msg) {
        return new BaseResult<>(code, msg, null);
    }

    public static <T> BaseResult<T> buildWithParam(ResponseParam param) {
        return new BaseResult<>(param.getCode(), param.getMsg(), null);
    }

    public int getCode() {
        return code;
    }

    public void setCode(int code) {
        this.code = code;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public T getData() {
        return data;
    }

    public void setData(T data) {
        this.data = data;
    }



    public static class ResponseParam {
        private int code;
        private String msg;

        private ResponseParam(int code, String msg) {
            this.code = code;
            this.msg = msg;
        }

        public static ResponseParam buildParam(int code, String msg) {
            return new ResponseParam(code, msg);
        }

        public int getCode() {
            return code;
        }

        public void setCode(int code) {
            this.code = code;
        }

        public String getMsg() {
            return msg;
        }

        public void setMsg(String msg) {
            this.msg = msg;
        }
    }

}

@PatchMapping(value="/message/text")
public BaseResult<Message> patch(Message message) {
    Message messageResult=this.messageRepository.updateText(message);
    return BaseResult.successWithData(messageResult);
}
属性名称 备注
value 属性描述
name 如果配置覆盖属性名称
allowableValues 允许的值
access 可以不配置
notes 没有使用
dataType 数据类型
required 是否为必传参数
position 显示的顺序位置
hidden 是否因此
example 举例
readOnly 只读
reference 引用

源码请查看 : https://github.com/MissWangLove/SpringBoot

springboot整合swagger

本文github位置:https://github.com/WillVi/springboot-swagger2-demo环境准备JDK版本:1.8Springboot版本:1.5.16Swagger及其Swagger-ui版本:2.6.1(关于swagger-ui版本每个版本的汉化方式可能有不同)默认url:http://localhost:8080/swagger-ui.htmlMaven依赖 查看详情

springboot整合swagger时,打开swagger-ui中文出现乱码

参考技术A问题记录:本例采用的swagger版本及相关组件问题出现原因:加入了Shiro后就出现了乱码,可能是在加入Shiro的时候编码选择错了,网上介绍的办法大多是在setting设置以及对tomcat的设置,但是还是不得,在先不探讨Shiro倒... 查看详情

springboot/git/linux/easycode

SpringBootSpringBoot整合MyBatisSpringBoot整合Swagger-UI好看的SwaggerUI【重要】好看的SwaggerUI(包括配置了token)–knife4jSpringBoot整合RedisSpringBoot整合SpringSecurity和JWT的1SpringBoot整合SpringSecurity和JWT的2Spring 查看详情

springboot整合swagger常见问题一

项目启动完,访问swagger-ui页面访问不到,这里可以给他指定一下,创建一个实体类即可@SuppressWarnings("deprecation")@Configurationpublic class WebMVCConfig extends WebMvcConfigurerAdapter {  &nb 查看详情

swaggerlearing-springboot整合swagger

学习了一下swagger。这是编写的Demo源码https://github.com/AmberBar/Learning/tree/master/swagger-learning/swagger需要的小伙伴可以clone直接运行访问地址http://localhost:9999/swagger-ui.html#/  查看详情

springboot学习——springboot快速整合swagger文档

@[toc]简介优点后端根据swagger语法,自动生成漂亮规范的接口文档。做交互测试。劣势侵入式的,影响程序运行,尤其是传参的时候。注意swagger分1.2版本和2.0版本,差异较大。swagger1.2即swagger-ui;swagger2.0即springfox-swagger。本文介... 查看详情

swagger-ui(代码片段)

一、Swagger-UI介绍Swagger-UI是HTML,Javascript,CSS的一个集合,可以动态地根据注解生成在线API文档。二、与springboot整合使用1、meven依赖<dependency><groupId>io.springfox</groupId><artifactId>springfox-swagger-ui</a 查看详情

springboot整合swagger,方便后端测试

参考技术A用Swagger能够在后端写好接口后进行测试,测试过程非常方便。Swagger是一个用于生成、描述和调用RESTful接口的Web服务。通俗的来讲,Swagger就是将项目中所有(想要暴露的)接口展现在页面上,并且可以进行接口调用和... 查看详情

spring系列整合swagger

...的文档7.访问http://ip:端口/项目名/swagger-ui.html即可1.新建springboot项目2.引入swagger的jar包3.定义swagger的配置类4.自定义controller生成文档5.访问http://ip:端口/项目名/swagger-ui.html即可 查看详情

springboot整合springfox3+knife4j,生成接口文档

参考技术A在这篇博客中,会记录springfox3的基本配置与使用;由于swagger-ui看得不是很习惯,额外引入了knife4j,使用增强版本的swagger的前端ui。注意@ConditionalOnProperty注解声明了当springfox.documentation.enabled为true时启用配置,而且默... 查看详情

springboot中部署swagger2和swagger-ui

1Gradle配置在dependencies中添加以下依赖:implementation("io.springfox:springfox-swagger2:2.7.0")implementation("io.springfox:springfox-swagger-ui:2.7.0") 具体的版本可以在https://mvnrepository.com/artifact/io.spring 查看详情

Spring Boot + Swagger + 自定义 swagger-ui.html

】SpringBoot+Swagger+自定义swagger-ui.html【英文标题】:SpringBoot+Swagger+customswagger-ui.html【发布时间】:2017-02-1922:38:10【问题描述】:我在将war应用程序迁移到springbootjar应用程序时遇到问题。我正在使用springboot1.4.1和swagger2.6.0。要在战... 查看详情

springspringboot2.6.4整合swagger3.0.0填坑

【Spring】SpringBoot2.6.4整合Swagger3.0.0填坑仓库配置使用如下依赖<!--swagger-ui--><dependency><groupId>io.springfox</groupId><artifactId>springfox-boot-starter</artifactId><vers 查看详情

如何更改 swagger-ui.html 默认路径

...alhost:8080/swagger-ui.html更改为localhost:8080/myapi/swagger-ui.html在springboot重定向对我很无助【问题讨论】:看看这个:gi 查看详情

13.9springboot集成swagger2中遇到的问题(代码片段)

13.9SpringBoot集成Swagger2中遇到的问题我们在使用SpringBoot集成Swagger2中,访问:http://127.0.0.1:8188/swagger-ui.html问题描述可能出现两种错误:1.页面显示默认报错页面。后台报错:NohandlerfoundforGET/swagger-ui.html2.显示Swagger空... 查看详情

[springboot系列]springboot如何整合ssmp

文章目录基于SpringBoot实现SSMP整合基于SpringBoot实现SSMP整合SpringBoot之所以好用,就是它能方便快捷的整合其他技术,这里我们先介绍四种技术的整合:整合JUnit整合MyBatis整合MyBatis-Plus整合Druid整合JUnitSpringBoot技术的定位用于简化... 查看详情

springboot2集成api文档工具swagger-ui(下)(代码片段)

接上篇swaggerUI提供了可视化界面帮助我们管理服务的访问路口,这就需要我们在代码中规范我们的书写格式。并且在swagger的界面上还能够模拟浏览器对服务进行访问。接口总览创建POST接口创建一个保存用户的接口@RequestMapping(val... 查看详情

springboot完成ssm整合之springboot整合junit(代码片段)

SpringBoot🍌掌握基于SpringBoot框架的程序开发步骤🍌使用SpringBoot配置信息修改服务器配置今日目标:基于SpringBoot的完成SSM整合项目开发第一步一、SpringBoot整合junit回顾Spring整合junit@RunWith(SpringJUnit4ClassRunner.class)@C... 查看详情