[ターン] swagger2スタートチュートリアル

 

swagger2が発生、説明、スタイルや視覚的なRESTfulなWebサービスを呼び出すための標準化と完全なフレームワークである、と今は春ブーツを統合するためにそれを使用します

 

 

 

役割:

 

1、ドキュメントインターフェイスは、自動的にオンライン生成します

 

図2に示すように、機能テスト

 

 

 

最初は普通のコメントを紹介しました

 

@Api注釈機能は、コントローラーをマークするために使用することができます

 

役割をマークするための@ApiOperation注釈方法

 

@ApilmplicitParamアノテーションは手動入力インタフェーステスト時間を回避するために、パラメータはデフォルトのパラメータ値に設定することができる、中国の意味で構成されることができるパラメータを記述するために使用されています

 

@ApilmplicitParams複数のパラメータが存在する場合、@ApilmplicitParamアノテーションの複数の使用を記載する必要があり、注釈は注釈@ApilmplicitParams複数の@ApilmplicitParamを必要とします

 

@ApiModel引数がオブジェクトである場合は、クラスオブジェクトにこのノートを追加する必要がありますされます

 

引数がオブジェクトである場合@ApiModelPropertyは、対応するプロパティにこのメモを追加する必要があるが、また、@ApiModelクラスのオブジェクトを追加する必要に位置しています

 

このパラメータを識別するための@ApiIgnore注釈を無視することができます

 

 

 

ここでは、使用方法を説明します

 

 

 

1、その依存関係の導入

 

<! -写接口文档的API - > 
        <依存> 
            <groupIdを> io.springfox </ groupIdを> 
            <たartifactId> springfox-swagger2 </たartifactId> 
            <バージョン> $ {swagger.version} </バージョン> 
            <除外> 
                <除外> 
                    <たartifactId>グアバ</たartifactId> 
                    <のgroupId> com.google.guava </ groupIdを> 
                </除外> 
            </除外> 
        </依存> 
        <依存性> 
            <のgroupId> com.google.guava </のgroupId > 
            <たartifactId>グアバ</たartifactId>
            <バージョン> $ {guava.version} </バージョン> 
        </依存> 
        <! -界面支持- >
        <依存性> 
            <のgroupId> io.springfox </のgroupId> 
            <たartifactId> springfox-闊歩-UI </たartifactId> 
            <バージョン> $ {swagger.version} </バージョン> 
        </依存>

 

 

 

2、EnableSwagger2マッピングおよび構成パス、スキャンインターフェースに未知の、ウェブサイトの情報文書@注釈を開きます

 

パッケージio.xiongdi.config; 

輸入io.swagger.annotations.ApiOperation;
輸入org.springframework.context.annotation.Bean;
輸入org.springframework.context.annotation.Configuration。
輸入springfox.documentation.builders.ApiInfoBuilder。
輸入springfox.documentation.builders.PathSelectors。
輸入springfox.documentation.builders.RequestHandlerSelectors。
輸入springfox.documentation.service.ApiInfo;
輸入springfox.documentation.service.ApiKey。
輸入springfox.documentation.spi.DocumentationType。
輸入springfox.documentation.spring.web.plugins.Docket。
インポートspringfox.documentation.swagger2.annotations.EnableSwagger2; 

インポートjava.util.ArrayListのの、
 インポートjava.util.Listに; 

/ ** 
 * @author wujiaxing 
 * <P> 
 * 3つのステップだけSwagger2使用
 * 1を導入Swaggerr依存
 *図2に示すように、コンフィギュレーション整理豆
 * 3、変性@Api他の注釈を使用して
 * </ P> 
 * / 
@Configuration 
@ EnableSwagger2 
パブリック クラスSwaggerConfig { 

    @Bean 
    公共ドケットcreateRestApi(){
         戻り 新しい新しいドケット(DocumentationType.SWAGGER_2)
                ).Selectを(
                // メソッドは、インターフェイスのドキュメントを生き残るためにApiOperationコメントが必要です
                .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation。クラス))
                 // パス任意のスタイルを使用する
                .paths(PathSelectors.any())
                .build()
                //を私たちのAPIを保護する方法を、3つの認証(APIKEY、にBasicAuth、OAuthの)があります
                。 securitySchemes(セキュリティ())
                 // 基本的な情報インターフェース文書
                .apiInfo(apiInfo()); 
    } 

    / ** 
     *インターフェース文書の詳細
     * 
     * @return 
     * / 
    プライベートapiInfo apiInfo(){
         返す 新しい新を。ApiInfoBuilder()タイトル( "兄弟足浴").DESCRIPTION( "XD-API文档").termsOfServiceUrl( "のhttp://www.localhost:8002").version( "1.0.0" ).build(); 
    } 

    プライベートリスト<APIKEY> セキュリティ(){ 
        のArrayList <APIKEY> apiKeys = 新規のArrayList <> (); 
        apiKeys.add(新しい APIKEY( "トークン"、 "トークン"、 "ヘッダ" ))。
        リターンapiKeys。
    } 
}

 

 

 

3、注釈を作成する識別インターフェイス文書を使用して

 

パッケージio.xiongdi.controller。

輸入io.swagger.annotations.Api;
輸入io.swagger.annotations.ApiOperation;
輸入io.xiongdi.annotation.Login;
輸入io.xiongdi.common.utils.R;
輸入io.xiongdi.common.validator.ValidatorUtils。
輸入io.xiongdi.form.LoginForm;
輸入io.xiongdi.service.TokenService;
輸入io.xiongdi.service.UserService;
輸入org.springframework.beans.factory.annotation.Autowired;
輸入 org.springframework.web.bind.annotation *。;
輸入springfox.documentation.annotations.ApiIgnore; 

インポートA java.util.Map; 

/ ** 
 * @author wujiaxing 
 * @date 2019年7月7日
 * / 
@Api(タグ = "ログ・インタフェース" 
@RequestMapping( "/ API" 
@RestController 
パブリック クラスApiLoginController { 

    @Autowired 
    プライベートtokenService tokenService; 
    @Autowired 
    プライベートUserServiceのそのUserServiceの、

    @RequestMapping( "ログイン" 
    @ApiOperation( "ログイン" 公共R&LTログイン(@RequestBody loginForm loginForm){
         // サーバフォーム検証 
        するSystem.out.println(「入力されたログイン"+loginForm); 
        ValidatorUtils.validateEntity(loginForm); 
        // ログイン行う 
        地図<文字列、オブジェクト>地図= ; userService.login(loginForm)

        リターンR.ok(マップ); 
    } 

    / ** 
     * <P> 
     要求アウト*ロギングをトークンテープ
     * @RequestAttributeアクセスが注釈は、フィルタやインターセプタは、属性を既存の作成を示している
     * </ P> 
     * @param のuserId 
     * @return 
     * / 
    @login 
    @ApiOperation( "ログイン" 
    (@RequestMapping "ジンバブエログアウト" 公的 R&LTジンバブエログアウト(@RequestAttribute( "はuserId")@ApiIgnore ロング USERID){
        tokenService.expireToken(USERID)。
        リターンR.ok(); 
    } 
}

 

以下のためのパッケージ変更io.xiongdi.form; 

インポートio.swagger.annotations.ApiModel;
 インポートio.swagger.annotations.ApiModelProperty;
 インポートlombok.Data; 

インポートjavax.validation.constraints.NotBlank; 

/ ** 
 *ログインフォーム
 * @author wujiaxing 
 * 2019年6月30日@date 
 * / 
@Data 
@ApiModel(値 =「ログインフォーム」パブリック クラスLoginForm { 

    @ApiModelProperty(値 =「携帯電話番号」
    @NotBlank(メッセージ =「電話番号が空にすることはできません」プライベート文字列モバイル; 

    @ApiModelProperty(値=「パスワード」
    @NotBlank(メッセージ =「パスワードが空白でない」プライベート文字列のパスワード; 
}

 

 

 

4.通常、その上に3段階以上のように構成していますが、クロスドメインを設定している場合は、設定の静的リソースに必要が手放します

 

パッケージio.xiongdi.config; 

輸入io.xiongdi.interceptor.AuthorizationInterceptor;
輸入io.xiongdi.resolver.LoginUserHandlerMethodArgumentResolver;
輸入org.springframework.beans.factory.annotation.Autowired;
輸入org.springframework.context.annotation.Configuration。
輸入org.springframework.web.method.support.HandlerMethodArgumentResolver;
輸入org.springframework.web.servlet.config.annotation.CorsRegistry;
輸入org.springframework.web.servlet.config.annotation.InterceptorRegistry;
輸入org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
インポートorg.springframework.web.servlet.config.annotation.WebMvcConfigurer; 

インポートjava.util.Listに; 

/ ** 
 * @author wujiaxing 
 * <P> 
 *この設定を構成することができるベースインターセプター、パーサパラメータ、戻り値リゾルバ、クロスドメインのサポート、など
 * </ P> 
 * / 
@Configuration 
パブリック クラス WebMvcConfig 実装WebMvcConfigurer { 

    @Autowired 
    プライベートauthorizationInterceptor authorizationInterceptor; 
    @Autowired 
    プライベートloginUserHandlerMethodArgumentResolver loginUserHandlerMethodArgumentResolver; 

    / ** 
     *クロスドメイン構成であれば、この構成が増加
     * @param レジストリ
      * /
    @Override 
    公共 のボイドaddResourceHandlers(ResourceHandlerRegistryレジストリ){ 
        registry.addResourceHandler( "/static/**").addResourceLocations("/static/" ); 
        registry.addResourceHandler( "/js/**").addResourceLocations("/js/" ); 
        registry.addResourceHandler( "威張っ-ui.html")addResourceLocations。( "クラスパス:/ META-INF /リソース/" ); 
        (registry.addResourceHandler "/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars" );

    
    公共 のボイドaddInterceptors(InterceptorRegistryレジストリ){ 
        registry.addInterceptor(authorizationInterceptor).addPathPatterns( "/ ** / API" ); 
    } 

    / ** 
     *跨域支持配置
     * @param レジストリ
      * / 
    @Override 
    公共 ボイドaddCorsMappings(CorsRegistryレジストリ){ 
        (registry.addMapping "/ **")。allowCredentials().allowedOrigins( "*")。allowedMethods( "GET"、 "PUT"、 "削除"、 "POST"、 "OPTIONS")MAXAGE(3600。 )。

    
    @Override 
    公共 ボイド addArgumentResolvers(一覧<HandlerMethodArgumentResolver> レゾルバ){ 
        resolvers.add(loginUserHandlerMethodArgumentResolver)。
    } 
}

 

 

 

このように、基本的な設定が完了している、アクセスはlocalhost:8080 /威張っ-ui.html

 

 

 


---------------------
著者:子供たちからも、コード叔母書きたい
CNBLOGS:出典
元ます。https://www.cnblogs.com/wujiaxing/p/を11180361.html
免責事項:この記事は著者のオリジナル記事です、ボーエンのリンクを添付してください、再現!
コンテンツ分析:CSDN、CNBLOGのブログ記事は、キープラグ復刻しました

おすすめ

転載: www.cnblogs.com/admans/p/11963690.html