LoginSignup
8
9

More than 5 years have passed since last update.

Spring MVC integration for Swaggerのバージョン2をSpringBootで実行する

Last updated at Posted at 2015-04-05

はじめに

Spring MVC integration for Swagger(https://github.com/springfox/springfox )のversion2のチュートリアル(https://github.com/springfox/springfox/blob/master/transitioning-to-v2.md )が分かりにくいので補足用のメモ。

利用ライブラリ

mavenリポジトリとして http://oss.jfrog.org/artifactory/oss-snapshot-local/ を設定。現在のところsnapshotしかないので、snapshotの設定を利用します。

SpringのConfig

SwaggerSpringMvcPluginを使う方式から、Docketというクラスを使う方式に変更されている。SpringSwaggerConfigは不要になっています。
Configファイルで使うアノテーションは、@EnableSwagger2になっています。
Docketには、API一覧を作る対象を設定するpathsを設定します。これはサンプルでは分かりにくいですが、Google GuavaのPredicateを使って記述するようになっています。com.google.common.base.Predicatesをstaticインポートすると、基本的な構文(orなど)が使えるようになりますので、これでパスを設定します。
またサンプルにある、Docket#groupName("business-api")という設定ですが、これはグループ分けができる機能で、URLパラメータに?group=business-apiとすることで、指定のDocketに対するAPI一覧を取得することができます。

ApiInfoですが、引数が増えていますのでv1からの移行であれば適当にString型の引数を足します。

import static com.google.common.base.Predicates.containsPattern;
import static com.google.common.base.Predicates.or;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

import com.google.common.base.Predicate;

@Configuration
@EnableSwagger2
public class Swagger2Config {

    @Bean
    public Docket swaggerSpringMvcPlugin() {
        return new Docket(DocumentationType.SWAGGER_2)
                .select().paths(paths()).build().apiInfo(apiInfo());
        //groupName("business-api")でURLパラメータ?group=businessでアクセスできる
    }

    @SuppressWarnings("unchecked")
    private Predicate<String> paths() {
        return or(containsPattern("/*"));
    }

    private ApiInfo apiInfo() {
        ApiInfo apiInfo = new ApiInfo("My API", "",
                "terms of service", "", "", "", "");
        return apiInfo;
    }
}

アクセスURL

以前はhttp://localhost/api-docsでしたが、version2からは http://localhost/v2/api-docs になっています。Docketに対してgroupNameメソッドでグループ指定した場合は、 http://localhost/v2/api-docs?group=グループ名 でアクセスします。

8
9
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
9