先後端分離的時候,須要創建契約,Swagger可達到該目的(略)。php
創建Rest接口後,經過swagger-codegen項目能夠自動生成對應的客戶端代碼(c++、php、java、js、node等等),java
關於swagger-codegen項目的使用,發現中文文檔較少,追根述源後,發現其中至關一部分同出一轍。node
親自摸索使用後,記錄一下步驟,利己利人。c++
swagger-codegen項目地址: https://github.com/swagger-api/swagger-codegengit
項目文檔(README.md)說的比較詳細,可是重複的地方太多,容易讓新手搞暈。github
其實,文檔內容能夠簡化爲以下步驟(凡‘略’,皆不予理睬):apache
【注意】如下步驟,均在Windows系統中操做,生成java客戶端代碼,其餘語言相似;英文很差,有些不會翻譯,故保留英文原文;json
一、Table of contents(略)後端
二、Compatibility(略)api
三、Prerequisites
3.一、從maven倉庫下載swagger-codegen的jar文件,以下
<!-- https://mvnrepository.com/artifact/io.swagger/swagger-codegen -->
<dependency>
<groupId>io.swagger</groupId>
<artifactId>swagger-codegen</artifactId>
<version>2.2.1</version>
</dependency>
放到本地目錄(好比D:\env\swagger-codegen-cli-2.2.1.jar);
3.二、本機安裝JDK7+,並設置$PATH(好比:D:\Java\jdk1.8.0_60\bin;);
3.三、本機安裝Maven3.3.3+,並設置$PATH(好比:D:\apache-maven-3.3.3\bin;);
四、Building(略)
五、Docker(略)
六、Homebrew(略)
七、Getting Started
dos窗口中,執行以下命令(Windows系統下,換行符無效,必須寫在同一行):
java -jar D:\env\swagger-codegen-cli-2.2.1.jar generate
-i http://petstore.swagger.io/v2/swagger.json
-l java
-o D:\swagger-client
--model-package com.xxx.client.model
--api-package com.xxx.client.api
【參數說明】
-jar 指定 swagger-codegen-cli-2.2.1.jar 的位置,絕對路徑、相對路徑都可;
-i 指定 swagger.json 的位置,本地路徑、網絡路徑都可;
-l 指定客戶端代碼的語言;
-o 指定代碼生成的位置;
--model-package 指定model代碼的包名;
--api-package 指定api代碼的包名;
八、Workflow Integration(略)
九、Github Integration(略)
【補充後續操做步驟】
十、將生成的代碼拷貝到項目中(api、model、test)
十一、pom.xml添加依賴(僅操做一次)
<!-- swagger-begin -->
<dependency>
<groupId>io.swagger</groupId>
<artifactId>swagger-jaxrs</artifactId>
<version>1.5.9</version>
</dependency>
<dependency>
<groupId>io.swagger</groupId>
<artifactId>swagger-annotations</artifactId>
<version>1.5.9</version>
</dependency>
<dependency>
<groupId>com.squareup.okhttp</groupId>
<artifactId>okhttp</artifactId>
<version>2.7.5</version>
</dependency>
<dependency>
<groupId>com.squareup.okhttp</groupId>
<artifactId>logging-interceptor</artifactId>
<version>2.7.5</version>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.6.2</version>
</dependency>
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
<version>2.9.3</version>
</dependency>
<!-- swagger-end -->
十二、修改ApiClient.java(通常來講,該文件無須覆蓋,僅操做一次)
12.一、修改屬性 basePath的值,本身的api根路徑;
12.二、若是須要ssl,或者url追加token,須要修改 buildUrl()方法;
1三、執行測試代碼便可(生成的測試代碼,方法體是空的,須要本身補充代碼);
【補充】
A、下載源代碼:
下載最新代碼
> git clone https://github.com/swagger-api/swagger-codegen.git
下載指定版本
> git clone --branch v2.2.1 https://github.com/swagger-api/swagger-codegen.git
B、查看swagger-codegen支持的命令
> java -jar swagger-codegen-cli-2.2.1.jar help
用法: swagger-codegen-cli <command> [<args>]
經常使用命令以下:
config-help 指定客戶端語言的可選項說明
generate 生成客戶端代碼命令
help 幫助
langs 顯式全部支持的語言
meta MetaGenerator. Generator for creating a new template set and configuration for Codegen. The output will be based on the language you specify, and includes default templates to include.
See 'swagger-codegen-cli help <command>' for more information on a specific command.
C、查看swagger-codegen的generate命令的可選項
> java -jar swagger-codegen-cli-2.2.1.jar help generate
NAME
swagger-codegen-cli generate - Generate code with chosen lang
SYNOPSIS
swagger-codegen-cli generate [options]
OPTIONS
-a <authorization>
當獲取遠程swagger定義時,添加受權頭信息;URL-encoded格式化的name,逗號隔開的多個值;
--auth <authorization>
同 -a;
--additional-properties <additional properties>
設置額外的屬性供模版使用;格式爲name=value,name=value;
--api-package <api package>
指定生成的api類的包名;
--artifact-id <artifact id>
指定pom.xml的artifactId的值;
--artifact-version <artifact version>
指定pom.xml的artifact的版本;
-c <configuration file>
json格式的配置文件的路徑;文件爲json格式,支持的配置項因語言的不一樣而不一樣;
執行 config-help -l {lang} 命令查看詳細的配置項;
--config <configuration file>
同 -c;
-D <system properties>
指定系統屬性,格式爲name=value,name=value;
--group-id <group id>
指定pom.xml的groupId的值;
-i <spec file>
指定swagger描述文件的路徑,url地址或路徑文件;該參數爲必須;
--input-spec <spec file>
同 -i;
--import-mappings <import mappings>
specifies mappings between a given class and the import that should be used for that class,
格式type=import,type=import;
--instantiation-types <instantiation types>
設置實例類型映射,格式type=instantiatedType,type=instantiatedType.
例如(in Java):array=ArrayList,map=HashMap.換句話說,生成代碼時,array類型會實例化爲ArrayList;
--invoker-package <invoker package>
指定根包名稱;
-l <language>
指定生成客戶端代碼的語言,該參數爲必須;
--lang <language>
同 -l;
--language-specific-primitives <language specific primitives>
指定附加語言特定的原始類型,格式type1,type2,type3,type3.例如:String,boolean,Boolean,Double;
--library <library>
library template (sub-template);
--model-package <model package>
指定生成的model類的包名;
-o <output directory>
指定生成文件的位置(默認當前目錄);
--output <output directory>
同 -o;
-s
指定該參數表示不覆蓋已經存在的文件;
--skip-overwrite
同 -s;
-t <template directory>
指定模版文件所在目錄;
--template-dir <template directory>
同 -t;
--type-mappings <type mappings>
設置swagger類型與生成的代碼類型之間的映射,格式swaggerType=generatedType,swaggerType=generatedType.
例如: array=List,map=Map,string=String;
-v
指定verbose mode;
--verbose
同 -v;
D、查看java客戶端的可配置項
> java -jar swagger-codegen-cli-2.2.1.jar config-help -l java
CONFIG OPTIONS
sortParamsByRequiredFlag
Sort method arguments to place required parameters before optional parameters. (Default: true)
ensureUniqueParams
Whether to ensure parameter names are unique in an operation (rename parameters that are not). (Default: true)
modelPackage
package for generated models
apiPackage
package for generated api classes
invokerPackage
root package for generated code
groupId
groupId in generated pom.xml
artifactId
artifactId in generated pom.xml
artifactVersion
artifact version in generated pom.xml
sourceFolder
source folder for generated code
localVariablePrefix
prefix for generated code members and local variables
serializableModel
boolean - toggle "implements Serializable" for generated models (Default: false)
bigDecimalAsString
Treat BigDecimal values as Strings to avoid precision loss. (Default: false)
fullJavaUtil
whether to use fully qualified name for classes under java.util.
This option only works for Java API client (Default: false)
hideGenerationTimestamp
hides the timestamp when files were generated
dateLibrary
Option. Date library to use
joda - Joda
legacy - Legacy java.util.Date
java8-localdatetime - Java 8 using LocalDateTime (for legacy app only)
java8 - Java 8 native
useRxJava
Whether to use the RxJava adapter with the retrofit2 library. (Default: false)
library
library template (sub-template) to use (Default: okhttp-gson)
jersey1 - HTTP client: Jersey client 1.19.1. JSON processing: Jackson 2.7.0
feign - HTTP client: Netflix Feign 8.16.0. JSON processing: Jackson 2.7.0
jersey2 - HTTP client: Jersey client 2.22.2. JSON processing: Jackson 2.7.0
okhttp-gson - HTTP client: OkHttp 2.7.5. JSON processing: Gson 2.6.2
retrofit - HTTP client: OkHttp 2.7.5. JSON processing: Gson 2.3.1 (Retrofit 1.9.0).
IMPORTANT NOTE: retrofit1.x is no longer actively maintained so please upgrade to 'retrofit2' instead.
retrofit2 - HTTP client: OkHttp 3.2.0. JSON processing: Gson 2.6.1 (Retrofit 2.0.2).
Enable the RxJava adapter using '-DuseRxJava=true'. (RxJava 1.1.3)
E、查看swagger-codegen支持的客戶端語言
> java -jar swagger-codegen-cli-2.2.1.jar langs
(結果略)
或參考 https://github.com/swagger-api/swagger-codegen/wiki/API-client-generator-HOWTO
F、服務器端代碼生成,參考https://github.com/swagger-api/swagger-codegen/wiki/Server-stub-generator-HOWTO
G、swagger支持的數據類型映射
http://swagger.io/specification/
參考代碼:DefaultCodegen.java
this.typeMapping = new HashMap();
this.typeMapping.put("array", "List");
this.typeMapping.put("map", "Map");
this.typeMapping.put("List", "List");
this.typeMapping.put("boolean", "Boolean");
this.typeMapping.put("string", "String");
this.typeMapping.put("int", "Integer");
this.typeMapping.put("float", "Float");
this.typeMapping.put("number", "BigDecimal");
this.typeMapping.put("DateTime", "Date");
this.typeMapping.put("long", "Long");
this.typeMapping.put("short", "Short");
this.typeMapping.put("char", "String");
this.typeMapping.put("double", "Double");
this.typeMapping.put("object", "Object");
this.typeMapping.put("integer", "Integer");
this.typeMapping.put("ByteArray", "byte[]");
this.typeMapping.put("binary", "byte[]");
遺留問題:
一、還不清楚如何將api數據類型和java的數據類型進行映射;
--------------------- 本文來自 wangjunjun2008 的CSDN 博客 ,全文地址請點擊:https://blog.csdn.net/wangjunjun2008/article/details/53200437?utm_source=copy