前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Spring boot Swagger2 配置使用实战

Spring boot Swagger2 配置使用实战

作者头像
create17
发布2020-06-09 09:56:59
1.6K0
发布2020-06-09 09:56:59
举报

每一个成功人士的背后,必定曾经做出过勇敢而又孤独的决定。

放弃不难,但坚持很酷~

今天来说一下 Spring boot 如何集成 Swagger 2,虽然网上有很多这样的教程,但觉得还是应该自己梳理一下,这样对知识的掌握比较牢靠。另外文章中也有我在开发中遇到的问题及解决方法,统一记录下来。 真的比 postman 省心,对于前后端联调、测试、用户来说都很便利。

一、集成 Swagger 2

1、添加 pom.xml 文件依赖

代码语言:javascript
复制
<!-- swagger ui -->
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>2.9.2</version>
</dependency>
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>2.9.2</version>
</dependency>
<dependency>
    <groupId>io.swagger</groupId>
    <artifactId>swagger-annotations</artifactId>
    <version>1.5.22</version>
</dependency>
<dependency>
    <groupId>io.swagger</groupId>
    <artifactId>swagger-models</artifactId>
    <version>1.5.22</version>
</dependency>

2、添加 Swagger java 配置

代码语言:javascript
复制
package com.hollysys.hollicube.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
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.swagger.web.*;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

/**
 * @author create17
 * @date 2020/6/3
 */
@Configuration
@EnableSwagger2
public class SwaggerConfig extends WebMvcConfigurationSupport {
    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.hollysys.hollicube.controller"))
                .paths(PathSelectors.any())
                .build();
    }

    /**
     * 隐藏UI上的Models模块
     */
    @Bean
    public UiConfiguration uiConfig() {
        return UiConfigurationBuilder.builder()
                .deepLinking(true)
                .displayOperationId(false)
                // 隐藏UI上的Models模块
                .defaultModelsExpandDepth(-1)
                .defaultModelExpandDepth(0)
                .defaultModelRendering(ModelRendering.EXAMPLE)
                .displayRequestDuration(false)
                .docExpansion(DocExpansion.NONE)
                .filter(false)
                .maxDisplayedTags(null)
                .operationsSorter(OperationsSorter.ALPHA)
                .showExtensions(false)
                .tagsSorter(TagsSorter.ALPHA)
                .validatorUrl(null)
                .build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("访问clientid管理、元数据管理、日志管理")
//                .description("")
//                .version("1.0")
//                .contact(new Contact("","",""))
//                .license("")
//                .licenseUrl("")
                .build();
    }

    /**
     * 防止@EnableMvc把默认的静态资源路径覆盖了,手动设置的方式
     *
     * @param registry
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        // 解决静态资源无法访问
        registry.addResourceHandler("/**")
                .addResourceLocations("classpath:/static/");
        // 解决swagger无法访问
        registry.addResourceHandler("/swagger-ui.html")
                .addResourceLocations("classpath:/META-INF/resources/");
        // 解决swagger的js文件无法访问
        registry.addResourceHandler("/webjars/**")
                .addResourceLocations("classpath:/META-INF/resources/webjars/");
    }
}

分析上述配置,我们需要在 java 类上指明 @Configuration、@EnableSwagger2 注解。

另外还需要指定 controller 的包路径。如果需要隐藏 Swagger ui 上的 Models 模块,则需要上面的 uiConfig() 方法。

为了防止 @EnableMvc 把默认的静态资源路径覆盖,还需要上面的 addResourceHandlers() 方法。

紧接着,我们就可以启动项目了,Swagger 2 ui 地址为:http://ip:port/swagger-ui.html 。

二、Swagger 常用注解

  • @Api(tags = "xxx相关接口") :修饰整个类,描述 Controller 的作用。
  • @ApiOperation("xxxx") :描述 api 接口方法。
  • @ApiModel("访问clientid表") :当 @RequestParam 参数多的时候,可以用对象来接收参数,通常用在 @RequestBody 的 对象 内。注意:@ApiModel 的 value 值需要保持唯一,否则会出现覆盖的情况。
  • @ApiModelProperty(value = "主键", required = true, hidden = true) :用对象接收参数时,描述 Model 对象的一个字段,也称为属性。
  • @ApiIgnore:用于 controller 层、controller 层方法、controller 层方法参数上,表示被 swagger ui 忽略。
  • @ApiParam(name = "", required = true, value = "clientid ID", hidden = true) :可用于描述单个参数,或者描述 @RequestBody 对象
    • name 为页面上的 Name
    • value 为页面上的 Description
  • @ApiImplicitParams({ @ApiImplicitParam(name = "name", value = "clientid名称"), @ApiImplicitParam(name = "clientid", value = "clientid编码"), @ApiImplicitParam(name = "description", value = "clientid描述信息") }) :适用于 @RequestParam 参数少的时候,参数多的时候可以用 @ApiModel 和 @ApiModelProperty 。

参考博客:https://www.cnblogs.com/fengli9998/p/7921601.html

三、个人小结

1、Swagger ui 页面上的 body 里面的 Model

注解 @ApiModel 和 @ApiModelProperty 是作用在 javaBean 上的,可以起解释说明,是否必选,是否隐藏的作用。在 swagger-ui 页面上的体现形式如下图所示:

2、controller 层 swagger 相关注解

@Api、@ApiOperation、@ApiParam、@ApiIgnore、@ApiImplicitParams 都是作用在 controller 层的注解。如下图所示:

3、PO、DTO、VO 说明及使用
  • PO(Persistant Object) 持久对象,用于表示数据库中的一条记录映射成的 java 对象,可以理解一个 PO 就是数据库中的一条记录;
  • DTO(Data Transfer Object)数据传输对象,前端调用时传输。
  • VO(Value Object)表现对象,用于表示一个与前端进行交互的 java 对象,只包含前端需要展示的数据。

关于 java 中常见的对象类型简述(DO、BO、DTO、VO、AO、PO)可参考:https://blog.csdn.net/uestcyms/article/details/80244407

当有多个 requestparam 参数的时候,我们用 DTO 对象接收参数比较方便,用 DTO 对象来精准无冗余地接收请求参数。

可能这里有朋友会疑问,为什么不用 PO 来接收请求参数呢?

因为 PO 中可能存在冗余字段,如果用 PO 来接收参数的话,冗余字段也会在 Swagger ui 页面上显示,用户体验并不好,所以我们用 DTO 来接收请求参数。

同理,为了避免返回给前端的数据存在冗余字段(即不需要展示的字段),我们可以使用 VO 来接收数据返回给前端进行交互。

本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2020-06-05,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 大数据实战演练 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 一、集成 Swagger 2
  • 二、Swagger 常用注解
  • 三、个人小结
    • 1、Swagger ui 页面上的 body 里面的 Model
      • 2、controller 层 swagger 相关注解
        • 3、PO、DTO、VO 说明及使用
        领券
        问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档