外部インターフェイスドキュメントは常に比較的原始的であり、基本的に手書きのドキュメントが渡されます。最近、私は新しいおもちゃを発見しました。これは、インターフェイスで多くのトラブルを節約できることを発見しました。
Swaggerは、便利なAPIドキュメントフレームワークです。手書きドキュメントの一方的およびエラー動作を回避して、最も包括的な方法でインターフェイスタイプを他の開発者に表示できます。
現在、Swagger2とSwagger2には2種類があります。 1はもっと面倒なので、使用することは考えません。この記事では、主にSwagger2を外部インターフェイスとして使用する2つの方法を記録します。後で確認してください。
1.従来のSpringMVCを使用して、Swagger2を統合します
1。メイブン依存関係
<! - springfox依存関係 - > <依存関係> groupid> com.fasterxml.jackson.core </groupid> <artifactid> jackson-core </artifactid> <version> 2.8.0 </version> </dependency> <deplency> <shiplency> <groupid> com.fasterxml.jackson.core </groupid> </groupid> </groupid> </groupid> <バージョン> 2.6.3 </version> </dependency> <dependency> groupid> com.fasterxml.jackson.core </groupid> <artifactid> jackson-annotations </artifactid> <version> 2.6.3 </version> </dependency> <依存関係> <groupid> springfox </groupid> <artifactid> springfox-swagger2 </artifactid> <バージョン> 2.4.0 </version> </dependency> <seprency> <groupid> io.springfox </groupid> <artifactid> springfox-swagge-ui </artifactid> <バージョン> 2.4.0
2. Spring-MVC.xmlに静的マッピング構成を追加します(実際、私はプロジェクトでこれを削除できます、状況が何であるかわかりません):
<! - 静的ファイルパス - > <MVC:リソース場所= "classpath:/meta-inf/resources/" mapping = "swagger-ui.html"/> <mvc:resources location = "classpath:/resources/" mapping = "/webjars/>>>>>
注:基本的なSpringMVC構成は投稿しません。 Swagger-ui.htmlインターフェイスが表示されている場合は、空白であることに注意する必要があります。Web.xmlのインターセプターの構成を確認してください。最初にSpringMVCを傍受する必要があり、次にインターフェイスが表示されます。
3。その後、Swagger2の構成クラスがあります:
@configuration @enableswagger2public class swaggerconfig拡張webmvcconfigurationsupport {@bean public docket createrestapi(){return new Docket(documentationType.swagger_2).apiinfo(apiinfo()).select() .apis(requesthandlerSelectors.basepackage( "net.laoyey.yyblog")).paths(pathselectors.any()).build(); } private apiinfo apiinfo(){return new apiinfobuilder().title( "yyblog project Restful apis").description( "yyblogプロジェクトAPIインターフェイスドキュメント").version( "1.0").build(); }}注:PATHSをPATHSELECTORS.NONE()に調整できる場合、すべてのインターフェイス情報を表示するわけではありません。
4。インターフェイス情報構成
つまり、SpringMVCコントローラーで関連するインターフェイス情報を構成します
@controller@requestmapping(value = "aitou")@api(description = "test service-account情報query")public class dailyoperationdatacontroller {logger logger = logger.getLogger(DailyOperationDatacontroller.class); @autowired privatedayaloperationdataservice dailyoperationdataservice; / * * @Apioperation(value = "interface description"、httpmethod = "interface request method"、response = "interface return parameter type"、notes = "interface release notes" * @apiparam(必須= "はパラメーターが必要です"、name = "パラメーター名"、value = "パラメーター具体説明" ={RequestMethod.POST,RequestMethod.GET}, value="/query/dailydata/{dataDate}") @ResponseBody public DailyOperationDataDto getDailyReportByDataDate(@PathVariable("dataDate") String dataDate) { try { return DailyOperationDataService.getDailyReportByDataDate(dataDate); } catch (例外e){logger.error(e.getmessage()、e);注:通常、Swagger2はスキャンパッケージの下にすべてのインターフェイスを表示します。ここでは、私はあまりにも多くのインターフェイスを表示しないようにするための別のパッケージになる外部インターフェイスです。もちろん、インターフェイス方法は、それが表示されないようにすることもできます。以下の関連注釈を見ることができます。
いくつかの一般的に使用されているメモ
@API:クラスの機能を説明するためにクラスで使用されます
@Apioperation:メソッドの機能を説明するための方法で使用されます
@APIIMPLICTPARAMS:メソッドにパラメーターの説明のセットを含めるために使用されます
@APIIMPLICTPARAM:@APIIMPLICTPARAMSアノテーションで使用、リクエストパラメーターパラメーターのさまざまな側面を指定します。
・クエリ - >リクエストパラメーターの取得:@RequestParam
・パス(RESTFULインターフェイス用) - >リクエストパラメーターの取得: @pathvariable
・ボディ(一般的には使用されていません)
・フォーム(一般的には使用されていません)
名前:パラメーター名データタイプ:パラメータータイプが必要:パラメーターを渡す必要があるかどうか値:パラメーター意味DefayourValue:パラメーターデフォルト値
@Apiresponses:一連の応答を表すために使用されます
@Apiresponse:@Apiresponsesで使用されますが、通常、エラー応答コードを表すために使用されます。
メッセージ:「リクエストパラメーターが記入されていない」などのメッセージ
応答:例外をスローするクラス
@Apiparam:単一のパラメーター説明
@Apimodel:モデルの情報を説明し、オブジェクトを使用してパラメーターを受信します(これは通常、@RequestBodyシナリオを使用して投稿を作成するときに使用されます。
@ApimodelProperty:モデルのプロパティを説明します
@Apiproperty:オブジェクトを使用してパラメーターを受信する場合、オブジェクトのフィールドを説明します
@Apiignore:この注釈を使用して、このAPIを無視します
基本的に、それは上記のすべてです。とても簡単ではありませんか?下の効果の写真を見てみましょう
2。スプリングブートを使用して、swagger2を統合します
上記は、従来のSpringMVCを使用してSwagger2を統合しました。最近の人気のあるスプリングブートメソッドについて話しましょう。実際、原則は同じです。
1。メイブン依存関係
<!--springfox dependency--> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>2.7.0</version> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <バージョン> 2.7.0 </version> </dependency>
これは、Springbootを使用して最近書いた個人プロジェクトの内部使用であり、使用された2.7.0を使用してバージョンで使用されています。
2.静的リソース構成を追加します
@configurationpublic class webmvcconfig extends webmvcconfigureradapter {/ ** *静的リソースパスとファイルをアップロードするパスを構成 * * * @param registry */ @Override public void addResourceHandlers(ResourceHandlerregistryレジストリ){ registry.addresourcehandler( "/static/**")。addresourcelocations( "classpath:/static/"); registry.addresourcehandler( "/upload/**")。addresourcelocations(environment.getProperty( "spring.resources.static-locations")); /*swagger-ui*/registry.addresourcehandler( "swagger-ui.html")。addresourcelocations( "classpath:/meta-inf/resources/"); registry.addresourcehandler( "/webjars/**")。addresourcelocations( "classpath:/meta-inf/resources/webjars/"); }}実際、それは最後の2つの文です。これを構成しない場合、Swagger-ui.htmlにアクセスすると、500または404のエラーが表示されます。覚えていない場合は、404でなければなりません。
3。Swagger2構成クラス
上記のように、基本的に違いはありません
@configuration@enableswagger2@enablewebmvcpublic class swaggerconfig extends webmvcconfigurationsupport {@bean public docket createrestapi(){return new docket(documentationtype.swagger_2).apiinfo(apiinfo()).select().select() .apis(requesthandlerSelectors.basepackage( "net.laoyeye.yyblog.web.frontend")).paths(pathselectors.none()).build(); } private apiinfo apiinfo(){return new apiinfobuilder().title( "yyblog project Restful apis")。 }}上記のパスに問題があることに注意してください。コピーはAPI(#^。^#)を直接表示しません
4。インターフェイス構成
/***フロントデスク記事コントローラー*コンビニエンスストアのおじいちゃん* @date 2018年5月5日* @website www.laoyeye.net*/ @api(description = "article query") @controller @requestmapping( "/article")パブリッククラスArticLecontroller {@autowired private artipervice artivechrice; @Autowired Private SettingService SettingService; @Autowired Private Cateservice Cateservice; @autowired private tagreferservice tagreferservice; @Autowiredプライベートユーザーサービスユーザーサービス。 @autowired private articlemapper articlemapper; @Autowiredプライベートコメントサービスコメントサービス。 @apioperation(value = "article query interface")@apiimplictparam(name = "id"、value = "article id"、required = true、datatype = "long")@getmapping( "/{id}")public string index(model model、 @pathvariable( "id")long id){try {try {artivice.updateviewsbyid(id); } catch(例外無視){} list <sitting> settings = settingservice.listall(); map <string、object> map = new hashmap <string、object>(); for(設定の設定:設定){map.put(setting.getCode()、sitent.getValue()); }記事記事= articlesvice.getarticlebyid(id); Model.Addattribute( "Settings"、Map); Model.Addattribute( "Catelist"、categoryservice.listallcate()); Model.Addattribute( "article"、article); Model.Addattribute( "Tags"、tagreferservice.listnamebyarticleid(article.getId())); Model.Addattribute( "author"、userservice.getnicknamebyid(article.getauthorid())); // model.addattribute( "記事"、articlemapper.listarticlebytitle(null)); Model.Addattribute( "Sirlys"、articlemapper.listarticlebytitle(null)); commentquery query = new CommentQuery(); query.setlimit(10); query.setPage(1); query.setarticleId(id); Model.Addattribute( "CONTURES"、commentservice.listcommentByarticleId(query)); 「フロントエンド/記事」を返します。 } @apioperation(value = "articlecomment query interface")@postmapping( "/comments")@responsebody public datagridresultコメント(commentquery query){//デフォルトの10 query.setlimit(10)を設定します。 commentservice.listcommentbyarticleid(query)を返します。 } @apioperation(value = "articlelid")@apiimplictparam(name = "articlid"、value = "articlid"、reby = true、datatype = "long") @responsebody public yyblogresult eppod(@requestparam reghtid){return return return eartervice.updeateaptn }}最後に、上記と同じレンダリングがあります。
pathselectors.none()が
pathselectors.any()is
インターフェイスコンテンツがレンダリングであるかどうかは一目で明らかであり、非常に簡潔で明確です。
最後に、私はswaggerドキュメントへの道を言うのを忘れたようです
プロジェクトがルートディレクトリにある場合:http:// localhost:8080/swagger-ui.html
ルートディレクトリではない場合は、http:// localhost:8080/your project name/swagger-ui.html
上記はこの記事のすべての内容です。みんなの学習に役立つことを願っています。誰もがwulin.comをもっとサポートすることを願っています。