springmvc与swagger的集成

Spring Cloud 学习笔记(五)--Gateway 实现多服务实例的 Swagger聚合 本人博客:https://cherishlife.com.cn/blog/28 有兴趣的朋友支持下,谢谢! 概述 Swagger 是一个规范和完整的框架,用于生成、描述、调用和可视化 RESTful 风格的 Web 服务。 本文主要介绍如何使用网关Gateway,实现将多个实例的Swagger聚合。 服务实例 pom依赖包配置 <!--Swagger-UI API文... 阅读详情

引子

由于我们公司在尝试着做前后端分离,那么后端的api文档是必须的,因此研究了一下swagger。swagger的2.0版本已经升级为springfox, 看这名字就知道springfox只能与springmvc做集成。

swagger介绍

  1. Swagger-Core,swagger最核心的部分,能够根据注解来生成swagger definition(json或者yaml格式)
  2. Swagger Codegen,顾名思义,根据swagger definition生成代码
  3. Swagger UI,用来展示swagger definition的web项目
  4. Swagger Editor,用来编辑swagger definition

本文主要涉及swagger-core,swagger-ui方面的内容

配置

  1. 首先添加maven依赖,通过maven repository可以知道兼容的spring的最低版本是4.1.8.RELEASE
<dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.4.0</version>
        </dependency>

        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-annotations</artifactId>
            <version>2.6.4</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.6.4</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
            <version>2.6.4</version>
        </dependency>

        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.4.0</version>
        </dependency>
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27

2.swagger config配置

package com.xxx.swagger;

import static com.google.common.collect.Lists.newArrayList;
import static springfox.documentation.builders.PathSelectors.ant;

import java.util.List;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;

import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.ImplicitGrantBuilder;
import springfox.documentation.builders.OAuthBuilder;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.ApiKey;
import springfox.documentation.service.AuthorizationScope;
import springfox.documentation.service.GrantType;
import springfox.documentation.service.LoginEndpoint;
import springfox.documentation.service.SecurityReference;
import springfox.documentation.service.SecurityScheme;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.contexts.SecurityContext;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger.web.ApiKeyVehicle;
import springfox.documentation.swagger.web.SecurityConfiguration;
import springfox.documentation.swagger2.annotations.EnableSwagger2;


@Configuration
@EnableWebMvc 
@EnableSwagger2 
@ComponentScan("com.xxx")
public class SpringfoxDocConfig {

    @Bean
    public Docket petApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .build()
                .securitySchemes(newArrayList(oauth()))
                .securityContexts(newArrayList(securityContext()));

    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("Springfox petstore API")
                .description("Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum " +
                        "has been the industry's standard dummy text ever since the 1500s, when an unknown printer "
                        + "took a " +
                        "galley of type and scrambled it to make a type specimen book. It has survived not only five " +
                        "centuries, but also the leap into electronic typesetting, remaining essentially unchanged. " +
                        "It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum " +
                        "passages, and more recently with desktop publishing software like Aldus PageMaker including " +
                        "versions of Lorem Ipsum.")
                .termsOfServiceUrl("http://springfox.io")
                .contact("springfox")
                .license("Apache License Version 2.0")
                .licenseUrl("https://github.com/springfox/springfox/blob/master/LICENSE")
                .version("2.0")
                .build();
    }

    @Bean
    SecurityContext securityContext() {
        AuthorizationScope readScope = new AuthorizationScope("read:pets", "read your pets");
        AuthorizationScope[] scopes = new AuthorizationScope[1];
        scopes[0] = readScope;
        SecurityReference securityReference = SecurityReference.builder()
                .reference("petstore_auth")
                .scopes(scopes)
                .build();

        return SecurityContext.builder()
                .securityReferences(newArrayList(securityReference))
                .forPaths(ant("/api/pet.*"))
                .build();
    }

    @Bean
    SecurityScheme oauth() {
        return new OAuthBuilder()
                .name("petstore_auth")
                .grantTypes(grantTypes())
                .scopes(scopes())
                .build();
    }

    @Bean
    SecurityScheme apiKey() {
        return new ApiKey("api_key", "api_key", "header");
    }

    List<AuthorizationScope> scopes() {
        return newArrayList(
                new AuthorizationScope("write:pets", "modify pets in your account"),
                new AuthorizationScope("read:pets", "read your pets"));
    }

    List<GrantType> grantTypes() {
        GrantType grantType = new ImplicitGrantBuilder()
                .loginEndpoint(new LoginEndpoint("http://petstore.swagger.io/api/oauth/dialog"))
                .build();
        return newArrayList(grantType);
    }

    @Bean
    public SecurityConfiguration securityInfo() {
        return new SecurityConfiguration("abc", "123", "pets", "petstore", "123", ApiKeyVehicle.HEADER, "", ",");
    }

}
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115

3.配置controller,这里仅举一例,详细完整的例子在springfox项目中的springfox-petstore模块里面

@Controller
@RequestMapping(value = "/api/user", produces = MediaType.APPLICATION_JSON_VALUE)
@Api(value = "/user", description = "Operations about user")
public class UserController {
  UserRepository userRepository = new UserRepository();

  static class UserRepository extends MapBackedRepository<String, User> {
  }

  @RequestMapping(value = "/{username}", method = GET)
  @ApiOperation(value = "Get user by user name", response = User.class)
  @ApiResponses(value = {
          @ApiResponse(code = 400, message = "Invalid username supplied"),
          @ApiResponse(code = 404, message = "User not found")})
  public ResponseEntity<User> getUserByName(
          @ApiParam(value = "The name that needs to be fetched. Use user1 for testing. ", required = true)
          @PathVariable("username") String username) {
    User user = userRepository.get(username);
    if (null != user) {
      return new ResponseEntity<User>(user, HttpStatus.OK);
    } else {
      throw new NotFoundException(404, "User not found");
    }
  }

}
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26

4.下载swagger-ui, 将dist目录copy到web项目中

5.测试一下,访问http://host:port/v2/api-docs应该可以下载swagger definition,访问http://host:port/swagger-ui/index.html会展现如下页面

swagger-ui

6.在有些项目中spring mvc的请求是以某一后缀(url-pattern, 例如 .do)结尾的, 这样就要做一些必要的修改,在swagger-ui.js中,修改如下

 opts.responseContentType = $('div select[name=responseContentType]', $(this.el)).val();
      opts.requestContentType = $('div select[name=parameterContentType]', $(this.el)).val();
      $('.response_throbber', $(this.el)).show();

      // here, add suffix
      var suffix = ".do";
      if (!this.model.path.endsWith(suffix)) {
          this.model.path = this.model.path + suffix;
      }

      if (isFileUpload) {
        $('.request_url', $(this.el)).html('<pre></pre>');
        $('.request_url pre', $(this.el)).text(this.invocationUrl);

        opts.useJQuery = true;
        map.parameterContentType = 'multipart/form-data';
        this.map = map;
        return this.model.execute(map, opts, this.showCompleteStatus, this.showErrorStatus, this);
      } else {
        this.map = map;
        return this.model.execute(map, opts, this.showCompleteStatus, this.showErrorStatus, this);
      }
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22

这样在swagger里面try it out的时候,即能发出正确的请求了

springfox源码走读

我们请求的地址是http://host:port/v2/api-docs,这个请求是Swagger2Controller来处理的

@ApiIgnore
  @RequestMapping(value = "${springfox.documentation.swagger.v2.path:" + DEFAULT_URL + "}",
      method = RequestMethod.GET, produces = { APPLICATION_JSON_VALUE, HAL_MEDIA_TYPE })
  public
  @ResponseBody
  ResponseEntity<Json> getDocumentation(
      @RequestParam(value = "group", required = false) String swaggerGroup,
      HttpServletRequest servletRequest) {

    String groupName = Optional.fromNullable(swaggerGroup).or(Docket.DEFAULT_GROUP_NAME);
    Documentation documentation = documentationCache.documentationByGroup(groupName);
    if (documentation == null) {
      return new ResponseEntity<Json>(HttpStatus.NOT_FOUND);
    }
    Swagger swagger = mapper.mapDocumentation(documentation);
    if (isNullOrEmpty(swagger.getHost())) {
      swagger.host(hostName(servletRequest));
    }
    return new ResponseEntity<Json>(jsonSerializer.toJson(swagger), HttpStatus.OK);
  }
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20

文档的数据是从documentationCache里面拿的,那么documentationCache的数据又是怎么添加进去的呢?在DocumentationPluginsBootstrapper中,其实是一个监听器,接收到ContextRefreshedEvent事件后会扫描所有的文档插件

@Override
  public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
    if (initialized.compareAndSet(false, true)) {
      log.info("Context refreshed");
      List<DocumentationPlugin> plugins = pluginOrdering()
          .sortedCopy(documentationPluginsManager.documentationPlugins());
      log.info("Found {} custom documentation plugin(s)", plugins.size());
      for (DocumentationPlugin each : plugins) {
        DocumentationType documentationType = each.getDocumentationType();
        if (each.isEnabled()) {
          scanDocumentation(buildContext(each));
        } else {
          log.info("Skipping initializing disabled plugin bean {} v{}",
              documentationType.getName(), documentationType.getVersion());
        }
      }
    }
  }
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18

那么scan的具体细节又是什么呢?在ApiDocumentationScanner中我们看到DocumentationBuilder先组装context的全局配置,然后apiListingScanner.scan(listingContext)会扫描所有的controller的api信息,具体操作在ApiListingScanner的scan方法中

public Documentation scan(DocumentationContext context) {
    ApiListingReferenceScanResult result = apiListingReferenceScanner.scan(context);
    ApiListingScanningContext listingContext = new ApiListingScanningContext(context,
        result.getResourceGroupRequestMappings());

    Multimap<String, ApiListing> apiListings = apiListingScanner.scan(listingContext);
    DocumentationBuilder group = new DocumentationBuilder()
        .name(context.getGroupName())
        .apiListingsByResourceGroupName(apiListings)
        .produces(context.getProduces())
        .consumes(context.getConsumes())
        .host(context.getHost())
        .schemes(context.getProtocols())
        .basePath(context.getPathProvider().getApplicationBasePath())
        .tags(toTags(apiListings));

    Set<ApiListingReference> apiReferenceSet = newTreeSet(listingReferencePathComparator());
    apiReferenceSet.addAll(apiListingReferences(apiListings, context));

    ResourceListing resourceListing = new ResourceListingBuilder()
        .apiVersion(context.getApiInfo().getVersion())
        .apis(from(apiReferenceSet).toSortedList(context.getListingReferenceOrdering()))
        .securitySchemes(context.getSecuritySchemes())
        .info(context.getApiInfo())
        .build();
    group.resourceListing(resourceListing);
    return group.build();
  }
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28

总的来说springfox的原理比较简单,但是在文档格式的规定上比较严格

参考

http://swagger.io/ 
https://github.com/swagger-api/swagger-core/wiki/Annotations

swagger与springmvc集成异常记录 这几天在项目中加入swagger,项目用的是springmvc,spring用的4.1.1,和大家一样,在网上找了个帖子,看了下步骤不复杂,就愉快的开始做了,但是,但是就是这样华丽而顺畅的入坑了,折腾好几个小时,记录下,希望能节省队友时间。 问题一 描述:页面提示Failed to load API definition,并且接口(http://127.0.0.1:8080/membe 阅读详情

相关推荐

springmvc集成Swagger自动生成api文档

springmvc集成Swagger自动生成api文档准备工作下载swaggerUI: https://github.com/swagger-api/swagger-ui maven项目中,添加pom依赖<dependencies> ... <dependency> <groupId>com.mangofactory</groupId> <artifa

4203

SpringMVC集成Swagger

一、集成方法 1.引入swagger依赖 在pom文件中引入swagger相关依赖 <!-- 配置swagger --> <dependency> <groupId>io.springfox</groupId&...

772

SpringMVC 集成 Swagger2

SpringMVC 集成Swagger2,相关说明可以打开 https://blog.csdn.net/everyday_hzg/article/details/80537902

springMVC集成swagger

springMVC集成swagger Swagger 是一个规范和完整的框架,用于生成、描述、调用和可视化 RESTful 风格的 Web 服务.是一个管理接口的框架,通过注解的方式、网页的形式自动帮我们生成接口相关的信息,相比以前文档的方式撰写的接口,swagger更加便捷、高效,省力。 springMVC集成swagger步骤如下: 1、在pom.xml文件中添加swagger2的依赖包 <!-- Jackson 2.5.1 --> <dependency> <grou

m0_37328048的博客 2361

Spring MVC+FastJson+Swagger集成的完整实例教程

主要给大家分享介绍了关于Spring MVC+FastJson+Swagger集成的完整实例教程,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧。

如何运用好DeepSeek为自己服务:智能增强的范式革命 || 目录

1.1 认知增强的三次浪潮1.2 DeepSeek认知增强模型1.3 人机认知耦合协议1.4 认知增强的数学基础。

𝓓𝓸𝓶𝓲𝓷𝓪𝓽𝓲𝓷𝓰 𝓐𝓵𝓵 𝓣𝓱𝓲𝓷𝓰𝓼 1234

在SpringMVC中集成Swagger2

为什么要使用Swagger2 在SpringMVC中集成Swagger2 引入依赖 添加Swagger2配置类 让Spring加载Swagger2配置类 访问Swagger2 为什么要使用Swagger2   在现在的项目开发中,后端越来越多的倾向于只提供api接口,而不进行页面等的搭建,编写操作,无论是采用前后端分离的开发模式,还是给移动端提供api接口等都是如此。而...

ZZY1078689276的专栏 635

SpringMvc 集成swagger2

本人刚接触到swagger2,如有什么不足的地方,希望大神帮我指出,谢谢

zhangjun19900306的博客 2061

晶振(晶体振荡器)测试方法详解

晶振测试方法分为无源和有源两种类型。无源晶振(两脚)需用示波器测试波形,重点关注正弦波形状、200mV-1.5Vpp幅值和频率精度;有源晶振(四脚)通电后直接输出方波。测试要点包括:示波器使用10X探头、AC耦合,带宽需5倍于晶振频率;万用表可初筛短路/开路;替换法是工程最有效方法。常见故障排查顺序:供电→复位→焊接→型号→负载电容→波形观察→更换晶振→MCU配置。负载电容需按公式计算匹配,示波器观察是核心测试手段。

jiujiujinyuxi的博客 949

C++中const和指针*的组合问题

今天在复习> 章节7.3的时候想到以前做的一个题,const和指针运算符*的若干种组合的合法性和意义问题,有点混淆,所以写了一个测试代码来验证一下,简单明了,一目了然。如果有什么遗漏的话欢迎指出。 首先是在Ubuntu14.04.1下用gcc 4.8.4编译运行的结果,编译器报错信息都附加在对应语句后面的注释里 /* * Note : Test for the combinations of

theColdOne的专栏 1087

SpringMvc之集成Swagger

1 搭建springmvc环境(此处省略) 2 导入额外需要的相关jar swagger-springmvc-1.0.0.jar swagger-models-1.0.0.jar swagger-core-1.5.0.jar swagger-annotations-1.3.11.jar jackson-core-2.4.4.jar jackson-annotations-2.4...

weixin_34160277的博客 85

ST MotorControl Workbench 6.2.1 自定义硬件配置避坑指南

本文详细介绍了ST MotorControl Workbench 6.2.1在自定义硬件配置中的常见问题与解决方案,涵盖功率板配置、采样电路校准、电机参数设置及代码生成避坑指南,帮助开发者高效完成电机控制项目开发。

red88的博客 1029

SpringMVC集成Swagger插件以及Swagger注解的简单使用

一、简介 Swagger是一个规范和完整的框架,用于生成、描述、调用和可视化 RESTful 风格的 Web 服务。总体目标是使客户端和文件系统作为服务器以同样的速度来更新。接口的方法,参数和模型紧密集成到服务器端的代码,允许API来始终保持同步。Swagger 让部署管理和使用功能强大的API从未如此简单。 我们的RESTful API就有可能要面对多个开发人员或多个开发团队:IOS开发...

qq_38999509的博客 911

C/C++李峋同款跳动的爱心代码(完整代码)

C++语言实现出李峋同款跳动的爱心的完整代码。

AIGC 10万+

【VoxCPM2】在Windows上从零搭建VoxCPM2 语音生成和语音克隆AI算法

建议你了解清楚VoxCPM2,再来考虑是否需要自己在本地搭建。

AnChenliang_1002的博客 764

SpringMVC集成Swagger2,初尝试和遇到的相关问题

之前项目的接口文档都是手动编写Word文档来做,制作成本较高,并且在进行版本迭代的时候进行标注和说明不是很方便,后来发现Swagger之后进行了简单的操作。 截止目前还未深度使用,本文仅记录初次使用Swagger的过程和遇到的问题,后续进行补充。 前言: 当前项目使用SpringMVC,集成Swagger2 Step1: 添加依赖包 io.spr

MikeLC7的博客 8899

YOLO26改进策略【模型轻量化】| 替换骨干网络为 2024轻量化网络MoblieNetV4:移动生态系统的通用模型

本文记录的是基于MobileNet V4的YOLO26目标检测轻量化改进方法研究。主要用于轻量化应用部署,相关轻量化改进与其整体架构非常适配。通过整合、以及优化的,能够在在不降低性能指标的前提下,降低计算成本。本文配置了原论文中、、、和五种模型,以满足不同的需求。MobileNetV4: Universal Models for the Mobile Ecosystem是一系列适用于移动生态系统的通用高效模型。以下将详细介绍其轻量化设计的出发点、原理、结构和优势:的实现代码如下: 四、修改步骤 4.1 修

Limiiiing的博客 855

springmvc快速集成swagger

1、先下载swagger https://download.csdn.net/download/twjjava/10903662 2、导入maven &lt;dependency&gt;         &lt;groupId&gt;com.mangofactory&lt;/groupId&gt;         &lt;artifactId&gt;swagger-springmvc&lt;/...

斜杠码农 1035

廖雪峰Python教程[完整版]

廖雪峰的python教程整理的,已经排好版了,而且还是完整的,适合小白

OV9734 DATASHEET,完整规格书

OV9734完整规格书,包括电气参数,尺寸规格,寄存器配置表等

springMvc集成swagger问题记录

springMvc集成swagger问题记录 1. springMvc集成swagger springMvc集成swagger有几种方式,这里选取其中的一种。(默认springMvc项目搭建完毕,添加swagger) (1)swagger的maven依赖 &amp;lt;dependency&amp;gt; &amp;lt;groupId&amp;gt;io.springfox&amp;lt;/g...

jacklife的博客 863

TMS_WebGMaps_1.9.8.0_Full_Source

TMS_WebGMaps_1.9.8.0_Full_Source 全源码 delphi cbuilder

Swagger2之springMVC的简单集成

搭建一个springMVC的demo工程 demo工程中pom.xml配置 &lt;!-- 接口文档和UI --&gt; &lt;dependency&gt; &lt;groupId&gt;io.springfox&lt;/groupId&gt; &lt;artifactId&gt;springfox-swagger2&lt;/artifactId...

sunnyJam的专栏 391

关于SpringMVC项目集成Swagger2

SpringMVC集成Swagger2的注意事项(非Spring boot)

AIDA64SS的博客 529
上一篇: springfox Swagger 2
下一篇: 如何看待JHipster框架
hxpjava1
博客等级 码龄19年 1365粉丝 511原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值
⌂ 换网址