zoukankan      html  css  js  c++  java
  • spring boot集成Swagger

    JDK 8

    SPRING BOOT 2.5.3

    io.springfox:springfox-swagger2:2.9.2

    io.springfox:springfox-swagger-ui

    com.github.xiaoymin:swagger-bootstrap-ui:1.9.6

    --

    swagger官网

    伟大的Coder!

    起步

    添加依赖包:来自博客园

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

    mvnrepository截图:

    2.9.2不是最新版了。

    包依赖关系:

    启动项目,访问:http://localhost:port/swagger-ui.html

    弹出了一个窗口,无法关闭。

    停止运行项目,才可以关闭。来自博客园

    swagger-ui.html 是一个网页,来自下面的依赖包:为什么不直接使用 swagger包呢?需要UI?

    添加了依赖包,什么也没做,就出现了上面的情况。来自博客园

    接下来,添加配置。

    配置1:空白配置

    import org.springframework.context.annotation.Configuration;
    
    import springfox.documentation.swagger2.annotations.EnableSwagger2;
    
    @Configuration
    @EnableSwagger2
    public class SwaggerConfig {
    
    }

    启动项目,此时,日志输出下面的信息:来自博客园

    pertySourcedRequestMappingHandlerMapping : Mapped URL path [/v2/api-docs] onto method 
    [springfox.documentation.swagger2.web.Swagger2Controller#getDocumentation(String, HttpServletRequest)]

    再次访问上面的网页 /swagger-ui.html:此时,打开了页面,显示了一些接口信息

    最后两个接口的响应内容是 项目的接口信息,返回后,再由页面展示出来。来自博客园

    上面的 compony-controller 是自己开发的接口,其它的是系统自动存在的,因为配置是空白的,所以,全部都展示出来了。

    点击 compony-controller 可以查看其下的接口,点击接口,可以查看接口的相信信息:

    配置2:更多配置

    SwaggerConfig.java
    package org.zl.mybatis.use.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;
    
    /**
     * Swagger配置
     * @author ben
     * @date 2021-11-25 20:37:54 CST
     */
    @Configuration
    @EnableSwagger2
    public class SwaggerConfig {
    
    	private String appBasePackage = "org.zl.mybatis.use";
    	
    	@Bean
    	public Docket createRestApi() {
    		return new Docket(DocumentationType.SWAGGER_2)
    				.apiInfo(apiInfo())
    				.select()
    				// 搜索包名:本项目基础package
    				.apis(RequestHandlerSelectors.basePackage(appBasePackage))
    				// 包名下的任何路径
    				.paths(PathSelectors.any())
    				.build();
    	}
    	
    	private ApiInfo apiInfo() {
    		return new ApiInfoBuilder()
    				// 标题
    				.title("S.B.项目")
    				// 描述
    				.description("Swagger使用")
    				// 版本
    				.version("1.0.0")
    				// 联系人信息
    				.contact(new Contact("ben", "http://localhost:10000", "ben@localhost"))
    				.build();
    	}
    	
    }
    

    访问页面,显示如下:没有基础包下的信息了,Swagger文档展示的信息更准确了。

    上面的UI看起来不太友好,于是,优秀的程序员开发了另一套UI:展示、调试(调用)接口都更为方便。来自博客园

    新UI依赖包:1.9.6是最新版,但很久没有更新了

    <dependency>
        <groupId>com.github.xiaoymin</groupId>
        <artifactId>swagger-bootstrap-ui</artifactId>
        <version>1.9.6</version>
    </dependency>

    说明,com.github.xiaoymin 下 发现还有很多其它项目。

    添加依赖包后,访问:http://localhost:port/doc.html

    这样通过划分TAB页,页面看起来更好看了。

    注意,上面是添加依赖包,此时,前面的 /swagger-ui.html 还是可以访问的。但是,没有必要用两个,那就选择后面一个吧——删除前面的依赖包。

    说明,上面的配置 也是我目前使用的最新的配置。

    在上面的Swagger的基础上,再合理使用Swagger的注解来介绍接口,可以更好地把接口展示给调用方。

    下面是一些示例:

    注意,@Data 是 lombok注释,提供了 getter、setter等——必须有这两类函数才会被 Swagger文档判断为 Model(数据模型)。

    @RestController
    @RequestMapping(value="/api/company")
    @Api(tags = {"公司接口"})
    @Slf4j
    public class ComponyController {
    
    	@ApiOperation(value = "1、根据ID查询公司")
    	@ApiImplicitParams(
    			@ApiImplicitParam(name = "id", value="公司ID", paramType = "query", required=true)
    			)
    	@GetMapping(value = "/getById")
    	public CompanyVO getById(@RequestParam Integer id) {
    		// TODO
    		return null;
    	}
    	
    	@ApiOperation(value = "2、根据ID查询公司(DTO)")
    	@GetMapping(value = "/getById/dto")
    	public CompanyVO getById(GetByIdDTO dto) {
    		// TODO
    		return null;
    	}
    	
    	@ApiOperation(value = "3、根据ID更新公司")
    	@PostMapping(value="/update")
    	public Integer updateCompany(@RequestBody UpdateCompanyDTO dto) {
    		return null;
    	}
    	
    }
    
    @Data
    public class GetByIdDTO {
    
    	@ApiModelProperty(value="公司ID", required = true)
    	private Integer id;
    	
    }
    
    @Data
    public class UpdateCompanyDTO {
    
    	@ApiModelProperty(notes="公司ID", required = true)
    	private Integer id;
    
    	@ApiModelProperty(notes="中文名称")
        private String nameCn;
    
    	@ApiModelProperty(notes="英文名称")
        private String nameEn;
    
    	@ApiModelProperty(notes="创建时间")
        private Date foundingTime;
    
    	@ApiModelProperty(notes="创建人")
        private String founder;
    	
    }
    
    @Data
    public class CompanyVO {
    
    	@ApiModelProperty(notes="ID")
        private Integer id;
    
    	@ApiModelProperty(notes="中文名称")
        private String nameCn;
    
    	@ApiModelProperty(notes="英文名称")
        private String nameEn;
    
    	@ApiModelProperty(notes="创建时间")
        private Date foundingTime;
    
    	@ApiModelProperty(notes="创建人")
        private String founder;
        
    }

    访问doc.html:

    注意,上面的Swagger运行时,会输出一条警告日志:

    2021-11-25 21:20:40.509  WARN 10384 --- [io-10000-exec-8] i.s.m.p.AbstractSerializableParameter    : 
    Illegal DefaultValue null for parameter type integer
    
    java.lang.NumberFormatException: For input string: ""
    	at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65) ~[na:1.8.0_202]

    解决:

    WARN日志来自 io.swagger 包,由于类型是 Integer导致。

    此时,提升io.swagger包的日志级别为ERROR即可。

    # application.properties中
    logging.level.io.swagger=error

    更多试验:

    1)请求参数在 请求头中;

    2)更高版本的Swagger支持;

    3)支持Spring Boot的WebFlux的Swagger;

    4)Swagger3 是什么?怎么用?

    Swagger虽然运行起来了,但是,下一个更重要的是——熟练使用Swagger的各种注解!两相结合,才可以为 调用方提供更好的接口文档。

    从此再也不用把接口文档写到 Word 里面了!

    还有一个优秀的开源软件 swagger-admin (现已停止维护):可以在继承各个项目的Swagger文档。

    》》》全文完《《《

    业界一定还有更高级的接口文档吧,欢迎大家分享!

    参考文档

    1、spring boot (2) 配置swagger2核心配置 docket

    by 1点

    2、【转】集成 swagger-bootstrap-ui后访问 doc.html页面404

    by 我家有只小熊二

    在开启安全功能时遇到无法访问的情况,按照本文的配置可以结局问题。

    3、swagger常用注解说明

    by Xiangdong_She

    4、

  • 相关阅读:
    Web大规模高并发请求和抢购的解决方案
    常用的排序算法
    Kafka中的消息是否会丢失和重复消费(转)
    excel操作之poi-ooxml
    spring-boot-configuration-processor 是干啥用的
    递归和尾递归的区别和原理(转)
    kafka接口文档和kafka教程
    quartz (从原理到应用)详解篇(转)
    Elastic-Job开发指南(转)
    SimpleDateFormat线程不安全及解决办法(转)
  • 原文地址:https://www.cnblogs.com/luo630/p/15605101.html
Copyright © 2011-2022 走看看