一、Swagger Codegen简介
Swagger Codegen是一个开源的代码生成器,根据Swagger定义的RESTful API可以自动建立服务端和客户端的连接。Swagger Codegen的源码可以在Github上找到。
GitHub: https://github.com/swagger-api/swagger-codegen
二、Swagger Codegen安装
首先机器上需要安装jdk,具体Java, version 7 or higher,然后在这里(https://oss.sonatype.org/content/repositories/releases/io/swagger/)找到需要的Swagger Codegen版本来安装,不过官方是推荐最新版本
只要下载一个cli的jar文件就可以了,例如, swagger-codegen-cli-2.2.1.jar(已共享到QQ群文件:301343109)。也可以直接在命令行里下载,例如

 Wget https://oss.sonatype.org/content/repositories/releases/io/swagger/swagger-codegen-cli/2.2.1/swagger-codegen-cli-2.2.1.jar

下载好了,运行

 java -jar swagger-codegen-cli-2.2.1.jar

根据返回结果可以看到Swagger Codegen支持的语言有很多: [android, aspnet5, async-scala, cwiki, csharp, cpprest, dart, flash, python-flask, go, groovy, java, jaxrs, jaxrs-cxf, jaxrs-resteasy, jaxrs-spec, inflector, javascript, javascript-closure-angular, jmeter, nancyfx, nodejs-server, objc, perl, php, python, qt5cpp, ruby, scala, scalatra, silex-PHP, sinatra, rails5, slim, spring, dynamic-html, html, html2, swagger, swagger-yaml, swift, tizen, typescript-angular2, typescript-angular, typescript-node, typescript-fetch, akka-scala, CsharpDotNet2, clojure, haskell, lumen, go-server]

三、Swagger Codegen的使用
查看Swagger Codegen的帮助信息

java -jar swagger-codegen-cli-2.2.1.jar help generate

查看Swagger Codegen支持的具体某个语言的使用帮助,拿java举例

java -jar swagger-codegen-cli-2.2.1.jar config-help -l java

复制代码

C:\Users\Administrator\Documents\swagger-coden>java -jar swagger-codegen-cli-2.3.0.jar help generate
NAMEswagger-codegen-cli generate - Generate code with chosen langSYNOPSISswagger-codegen-cli generate[(-a <authorization> | --auth <authorization>)][--additional-properties <additional properties>...][--api-package <api package>] [--artifact-id <artifact id>][--artifact-version <artifact version>][(-c <configuration file> | --config <configuration file>)][-D <system properties>...] [--git-repo-id <git repo id>][--git-user-id <git user id>] [--group-id <group id>][--http-user-agent <http user agent>](-i <spec file> | --input-spec <spec file>)[--ignore-file-override <ignore file override location>][--import-mappings <import mappings>...][--instantiation-types <instantiation types>...][--invoker-package <invoker package>](-l <language> | --lang <language>)[--language-specific-primitives <language specific primitives>...][--library <library>] [--model-name-prefix <model name prefix>][--model-name-suffix <model name suffix>][--model-package <model package>][(-o <output directory> | --output <output directory>)][--release-note <release note>] [--remove-operation-id-prefix][--reserved-words-mappings <reserved word mappings>...][(-s | --skip-overwrite)][(-t <template directory> | --template-dir <template directory>)][--type-mappings <type mappings>...] [(-v | --verbose)]OPTIONS-a <authorization>, --auth <authorization>adds authorization headers when fetching the swagger definitionsremotely. Pass in a URL-encoded string of name:header with a commaseparating multiple values--additional-properties <additional properties>sets additional properties that can be referenced by the mustachetemplates in the format of name=value,name=value. You can also havemultiple occurrences of this option.--api-package <api package>package for generated api classes--artifact-id <artifact id>artifactId in generated pom.xml--artifact-version <artifact version>artifact version in generated pom.xml-c <configuration file>, --config <configuration file>Path to json configuration file. File content should be in a jsonformat {"optionKey":"optionValue", "optionKey1":"optionValue1"...}Supported options can be different for each language. Runconfig-help -l {lang} command for language specific config options.-D <system properties>sets specified system properties in the format ofname=value,name=value (or multiple options, each with name=value)--git-repo-id <git repo id>Git repo ID, e.g. swagger-codegen.--git-user-id <git user id>Git user ID, e.g. swagger-api.--group-id <group id>groupId in generated pom.xml--http-user-agent <http user agent>HTTP user agent, e.g. codegen_csharp_api_client, default to'Swagger-Codegen/{packageVersion}}/{language}'-i <spec file>, --input-spec <spec file>location of the swagger spec, as URL or file (required)--ignore-file-override <ignore file override location>Specifies an override location for the .swagger-codegen-ignore file.Most useful on initial generation.--import-mappings <import mappings>specifies mappings between a given class and the import that shouldbe used for that class in the format of type=import,type=import. Youcan also have multiple occurrences of this option.--instantiation-types <instantiation types>sets instantiation type mappings in the format oftype=instantiatedType,type=instantiatedType.For example (in Java):array=ArrayList,map=HashMap. In other words array types will getinstantiated as ArrayList in generated code. You can also havemultiple occurrences of this option.--invoker-package <invoker package>root package for generated code-l <language>, --lang <language>client language to generate (maybe class name in classpath,required)--language-specific-primitives <language specific primitives>specifies additional language specific primitive types in the formatof type1,type2,type3,type3. For example:String,boolean,Boolean,Double. You can also have multipleoccurrences of this option.--library <library>library template (sub-template)--model-name-prefix <model name prefix>Prefix that will be prepended to all model names. Default is theempty string.--model-name-suffix <model name suffix>Suffix that will be appended to all model names. Default is theempty string.--model-package <model package>package for generated models-o <output directory>, --output <output directory>where to write the generated files (current dir by default)--release-note <release note>Release note, default to 'Minor update'.--remove-operation-id-prefixRemove prefix of operationId, e.g. config_getId => getId--reserved-words-mappings <reserved word mappings>specifies how a reserved name should be escaped to. Otherwise, thedefault _<name> is used. For example id=identifier. You can alsohave multiple occurrences of this option.-s, --skip-overwritespecifies if the existing files should be overwritten during thegeneration.-t <template directory>, --template-dir <template directory>folder containing the template files--type-mappings <type mappings>sets mappings between swagger spec types and generated code types inthe format of swaggerType=generatedType,swaggerType=generatedType.For example: array=List,map=Map,string=String. You can also havemultiple occurrences of this option.-v, --verboseverbose mode

利用Swagger Codegen根据服务生成客户端代码

`java -jar swagger-codegen-cli-2.2.1.jar generate -i http://petstore.swagger.io/v2/swagger.json -l java -o` samples/client/pestore/java

在上面这段代码里,使用了三个参数,分别是-i和-l和-o。

-i指定swagger描述文件的路径,url地址或路径文件;该参数为必须(http://petstore.swagger.io/v2/swagger.json是官方的一个例子,我们可以改成自己的服务)

-l指定生成客户端代码的语言,该参数为必须

-o指定生成文件的位置(默认当前目录)

除了可以指定上面三个参数,还有一些常用的:

-c json格式的配置文件的路径;文件为json格式,支持的配置项因语言的不同而不同

-a 当获取远程swagger定义时,添加授权头信息;URL-encoded格式化的name,逗号隔开的多个值

–api-package 指定生成的api类的包名

–artifact-id 指定pom.xml的artifactId的值

–artifact-version 指定pom.xml的artifact的版本

–group-id 指定pom.xml的groupId的值

–model-package 指定生成的model类的包名

-s 指定该参数表示不覆盖已经存在的文件

-t 指定模版文件所在目录

生成好的客户端代码

生成的这些文件里,src文件下的文件和pom.xml文件是对我们最有用的。把它们导入到我们习惯用的java编辑器里,这里以eclipse为例,下面是导入好的客户端的maven工程,和我们平常新建的maven工程一模一样(已共享到QQ群文件:301343109)。

但是自动生成的客户端代码并不能直接使用,需要我们做一些修改,特别是io.swagger.client.api包下的class类,我们需要把void替换成各自的model。

改好后,我们就可以运行客户端test下的测试代码,进行单元测试了。拿PetApiTest类来举例,运行它的addPetTest()方法。

可以看到测试成功。

2019.6.23 更新
我们会发现生成的默认包是io.swagger.client.api/module,而我们可能想要自己的包,怎么办呢?我看网上居然有人说要改源码,以下是那篇文章的内容。

这边我想说swagger也是一个比较成熟的产品了,也这么多人在用了,怎么可能连修改默认的包这个基础的需求都不提供呢,说明这篇文章的作者,根本就没看Swagger Codegen的帮助信息,上面明明已经列出来了,只需要生成代码的时候指定–api-package这个选项就好了。

命令我贴出来

java -jar swagger-codegen-cli-2.3.1.jar generate -i http://xxxx:8807/static/swagger.json -l java -o C:\Users\Administrator\Documents\xx-java-gen --api-package com.xxxx.client  --invoker-package com.xxxx.client.invoker --model-package com.xxxx.client.model

所以我们在学习和工作的时候,一定要灵活,多动脑。

swagger-codegen自动生成代码工具的介绍与使用相关推荐

  1. 自动生成代码工具 模板工具类

    自动生成代码工具 模板工具类 import java.io.BufferedWriter; import java.io.FileOutputStream; import java.io.Output ...

  2. 【MPC5744P】S32DS中Processor Expert自动生成代码工具使用教程(一) 开发环境搭建

    MPC5744P是NXP近几年推出来的主打安全功能的双核MCU,非常适合在汽车控制器相关产品中使用,非常强大.但是强大的同时,也意味着开发难度增大. MPC5744P外设功能相关的寄存器非常之多,且对 ...

  3. 使用mybatis-generator自动生成代码的方法介绍及踩坑

    mybatis-geneator是一款mybatis自动代码生成工具,可以通过配置,快速生成mapper和xml文件. 一. 使用maven插件 在pom.xml中添加mybatis-generato ...

  4. apt编译java_自动生成代码工具--APT

    APT(Annotation Processing Tool)注解处理器,是javac的一个工具,它用来在编译时扫描和处理注解(Annotation).它可以生成Java代码,同时这些代码会跟手工白那 ...

  5. Vue-Layout:可视化布局、自动生成代码工具

    按惯例,先上GIF: demo1 banner Vue-Layout 基于UI组件的Vue可视化布局.生成.vue代码的工具.jaweii.github.io/Vue-Layout/- GitHub ...

  6. mybatis自动生成代码工具

    https://pan.baidu.com/s/1c0cjDEK 转载于:https://www.cnblogs.com/lxcmyf/p/8580554.html

  7. 黑科技:进阶必备,推荐两款自动生成代码神器

    关注上方"测试开发技术",选择星标, 干货技术,第一时间送达! 最近两年,在互联网行业各大技术峰会上,都能看到关于工程效能这个概念,从侧面也反映出了研发效能已经逐渐被各企业所重视! ...

  8. vue可视化拖拽生成工具_GitHub - 1260215278/dragUI: 基于vuedraggable.js + uni 的可视化拖拽编程,自动生成项目,自动生成代码,自行导入第三方组件...

    dragUI 用于UNI可拖拽可视化编程 在线演示 效果图 基于 快速开始 参考uni官网安装普通uni项目(运行uni-app)运行到浏览器 另需要手动下载包npm install 项目目录 col ...

  9. mysql中怎样自动生成代码_MySql之自动生成CRUD代码

    MySql之自动生成CRUD代码 MyBatis能够通过获取MySql中的information_schema从而获取表的字段等信息,最后通过这些信息生成代码. 笔者受此启发,将MyBatis-Gen ...

最新文章

  1. android中文首字母排序,Android上汉字按拼音排序如何实现?
  2. mysql 普通索引和唯一索引_MySQL 普通索引和唯一索引的区别
  3. 年薪50万的程序员_这些年薪50万+的程序员都经历了什么?
  4. spring 配置文件无法加载,junit找不到xml配置文件java.lang.IllegalStateException: Failed to load ApplicationContext...
  5. android 锁屏解决方案,Android 实现锁屏的较完美方案
  6. C语言数组元素总和最大的连续子序列的算法(附完整源码)
  7. FFmpeg过滤器框架分析
  8. myeclipse深色模式_完善深色模式的调色板
  9. s查找mysql服务_MySQL菜鸟实录(一):MySQL服务安装实战
  10. 全国青少年信息学奥林匹克联赛
  11. 李迟2021年9月知识总结
  12. C++之 程序文件和预处理
  13. ISO-9001质量管理体系认证经验分享
  14. 手动实现获取微信openid
  15. 解决Source Not Found问题
  16. [C++]判断齐次坐标系中三点是否共线(三个向量是否共面)
  17. 《咏怀古迹五首·其三》.唐.杜甫
  18. 关键词搜索量是什么,如何看待关键词热度!
  19. h0206. 区间选点
  20. Windows照片查看器无法显示此照片,因为计算机上的可用内存可能不足。

热门文章

  1. 软件中的“黑马”,你知道的有哪些?
  2. 思岚科技—SLAMTEC未来服务机器人行业的“Intel”
  3. iptables指令逻辑详解
  4. 微信小程序点击跳转页面
  5. 基本运用(一个一个字读)
  6. 都2023了,Android 怎么还没有凉呀?
  7. uniapp/手机APP使用支付宝支付(服务端)
  8. 学习笔记2-Sisco硬件
  9. MUI返回页面未能及时刷新数据问题的解决办法
  10. 外部信号输入源阻抗与ADC内部开关电阻关系