Skip to content

Spring Boot 3 での springdoc-openapi 統合

問題概要

Spring Boot 3 アプリケーションに springdoc-openapi を追加する際、次の問題が発生します:

  • springdoc-openapi-ui 依存関係を追加しても動作しない
  • /swagger-ui.html エンドポイントにアクセスすると 404 エラーが発生する
  • ドキュメントが期待通りに表示されない

根本原因

Spring Boot 3 は Jakarta EE 9+ へ移行したため、springdoc-openapi-ui 1.x は互換性がありません。Spring Boot 3 では専用のモジュールが必要です。

解決方法

依存関係の変更

1. 不適切な依存関係を削除:

xml
<!-- 削除する依存関係 -->
<dependency>
    <groupId>org.springdoc</groupId>
    <artifactId>springdoc-openapi-ui</artifactId>
    <version>1.6.11</version>
</dependency>

2. 適切な依存関係を追加:

xml
<!-- Spring Boot 3用に修正した依存関係 -->
<dependency>
    <groupId>org.springdoc</groupId>
    <artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
    <version>2.0.0+</version>
</dependency>

互換性マトリックスの確認

バージョンの選択には公式互換性マトリックスを参照してください:

Spring Boot バージョンspringdoc-openapi バージョン
3.4.x2.7.x - 2.8.x
3.3.x2.6.x
3.2.x2.3.x - 2.5.x
3.1.x2.2.x
3.0.x2.0.x - 2.1.x
2.7.x1.6.0+

参考: 公式互換性マトリックス

基本設定の追加(任意)

application.properties に明示的にパスを設定:

properties
springdoc.api-docs.path=/api-docs
springdoc.swagger-ui.path=/swagger-ui.html
springdoc.swagger-ui.enabled=true

同等の application.yml 設定:

yaml
springdoc:
  api-docs:
    path: /api-docs
  swagger-ui:
    path: /swagger-ui.html
    enabled: true

エンドポイントの確認

正しい Swagger UI の URL にアクセス:

http://localhost:8080/swagger-ui.html

API ドキュメント(JSON)のURL:

http://localhost:8080/v3/api-docs

追加設定ケース

Spring Security を使用している場合

セキュリティ設定でエンドポイントを許可:

java
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
    http.authorizeHttpRequests(auth -> {
            auth.requestMatchers(
                    "/v3/api-docs/**", 
                    "/swagger-ui/**"
                ).permitAll();
            auth.anyRequest().authenticated();
        });
    return http.build();
}

WebFlux を使用している場合

適切な依存関係を選択:

gradle
// Gradleの場合
implementation 'org.springdoc:springdoc-openapi-starter-webflux-ui:2.x.x'

カスタム設定を追加する場合

@OpenAPIDefinition アノテーションと設定クラス:

java
@SpringBootApplication
@OpenAPIDefinition
public class MyApplication {
    public static void main(String[] args) {
        SpringApplication.run(MyApplication.class, args);
    }
}

@Configuration
public class SwaggerConfig implements WebMvcConfigurer {

    @Bean
    public OpenAPI customOpenAPI() {
        return new OpenAPI()
            .info(new Info()
                .title("API Documentation")
                .version("1.0")
                .description("詳細な説明"));
    }
}

トラブルシューティング

  • javax.servlet.http.HttpServletRequest エラー: 依存関係が間違っている可能性が高い
  • クッキー問題: ブラウザのキャッシュとクッキーをクリア
  • バージョン不一致: 公式互換性マトリックスで再確認
  • 404 エラー持続: 依存関係の再同期とプロジェクトのクリーンビルドを実行

備考: Kotlin 利用時は追加依存関係が必要:

xml
<dependency>
    <groupId>com.fasterxml.jackson.module</groupId>
    <artifactId>jackson-module-kotlin</artifactId>
</dependency>

参考リソース