Spring Boot 3でのSwagger 3実行方法
問題点
Spring Boot 3.0環境でspringfox-boot-starter
を使用すると、以下のような問題が発生します。
/swagger-ui.html
や関連URLへのアクセスで404エラー(ホワイトラベルエラーページ)が発生- 既知の問題として、GitHub Issuesでもレポートされている
- 根本原因: Spring Boot 3がJakarta EE 9を採用したことで、Springfox(Swagger)が互換性の問題を抱えているため
解決策: Springdoc OpenAPIの採用
Spring Boot 3ではSpringdoc OpenAPIが公式に推奨されるソリューションです。Springfoxの代わりに以下の手順で導入します。
依存関係の追加
Mavenの場合 (pom.xml
):
xml
<dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
<version>2.5.0</version> <!-- 最新バージョンを推奨 -->
</dependency>
Gradleの場合 (build.gradle
):
groovy
implementation 'org.springdoc:springdoc-openapi-starter-webmvc-ui:2.5.0'
バージョン選択のポイント
- Spring Boot 3にはSpringdoc v2.xが必要
- 最新バージョンを利用することを強く推奨
基本アクセスURL
以下のURLでSwagger UIにアクセス可能です。
text
http://localhost:8080/swagger-ui/index.html
必要に応じた設定
カスタムパスの設定
application.properties
でパスを変更可能:
properties
# APIドキュメント設定
springdoc.api-docs.path=/api-docs
springdoc.swagger-ui.path=/custom-docs
基本的なOpenAPI設定
java
@Configuration
@OpenAPIDefinition(
info = @Info(
title = "APIドキュメント",
version = "1.0.0",
description = "Spring Boot 3 REST APIドキュメント"
)
)
public class OpenApiConfig {
// 追加設定が必要な場合ここに記述
}
Spring Securityを使用している場合
Swagger関連エンドポイントへのアクセス許可が必要です。
java
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
return http
.authorizeHttpRequests(authorize -> authorize
.requestMatchers(
"/v3/api-docs/**",
"/swagger-ui/**",
"/swagger-ui.html"
).permitAll()
.anyRequest().authenticated()
)
// その他のセキュリティ設定...
.build();
}
重要な例外パターン
Springdocが使用する主要なパスエンドポイント:
/v3/api-docs/**
/v3/api-docs.yaml
/swagger-ui/**
/swagger-ui.html
よくある問題と対処法
1. IntelliJでキャッシュが原因で動作しない場合
- File > Invalidate Caches を選択
- Invalidate and Restart をクリック
- ターミナルで以下を実行:shell
mvn clean install -DskipTests
- アプリケーション再起動
2. 旧バージョンの依存関係が残っている場合
古いSpringdocやSpringfoxが残っていると衝突が発生します。
xml
<!-- 削除する依存関係の例 -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-boot-starter</artifactId>
</dependency>
<!-- 以下のような古いSpringdocも削除 -->
<dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-ui</artifactId>
</dependency>
高度な設定例
JWT認証を含むAPIのサンプル設定:
java
@Configuration
@OpenAPIDefinition(
info = @Info(
title = "REST API",
version = "1.0",
description = "Spring Boot 3 REST API"
),
security = {@SecurityRequirement(name = "bearerToken")}
)
@SecuritySchemes({
@SecurityScheme(
name = "bearerToken",
type = SecuritySchemeType.HTTP,
scheme = "bearer",
bearerFormat = "JWT"
)
})
public class OpenApiConfig {
// 追加設定
}
動作確認ポイント
- 依存関係が正しく追加されていること
- Spring Securityを使用している場合はエンドポイント許可設定があること
- サーバーのポート/コンテキストパスが正しいこと
/v3/api-docs
にアクセスしてJSONが返るか確認
text
http://localhost:8080/v3/api-docs
関連リソース
- 公式ドキュメント: https://springdoc.org/v2/
- ソースコード例: Springdoc GitHub Repository