0
0

RestControllerのswagger-uiでの名称変更

Posted at

デフォルトだと@RestControllerのクラス名がそのまま表示されるため、それを変更するには@Tagを使用する。

import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@Tag(name = "サンプルその1")
@RestController
public class Tag1SampleRest {

  @GetMapping("/foo/hoge")
  public String fooHoge() {
    return null;
  }

  @GetMapping("/foo/hoge222")
  public String fooHoge222() {
    return null;
  }
}

使用例は以下の通り。

swaggertag0001.jpg

なぜタグで表示名が変更できるのか? きちんと調べたわけではないが、タグの本来の用途は複数のエンドポイントを論理的なグループでまとめる、というものらしい。@RestController単位にタグを付与するとそれらエンドポイントがそのタグでグループされる、よって結果的にタグで表示名が変更できる、のだと思う。以下ドキュメントのtagsの項を参照。

なので、下記のように複数の@RestContollerにそれぞれ属するエンドポイントへ同一の@Tagを付与するとswagger-ui上ではそのグループとしてまとめて表示される。以下が使用例。

@RestController
public class Tag1SampleRest {

  @GetMapping("/foo/hoge")
  @Tag(name = "異なるRestControllerのエンドポイントをタグでまとめる")
  public String fooHoge() {
    return null;
  }

  @GetMapping("/foo/hoge222")
  public String fooHoge222() {
    return null;
  }
}
@RestController
public class Tag2SampleRest {

  @GetMapping("/bar/fuga")
  @Tag(name = "異なるRestControllerのエンドポイントをタグでまとめる")
  public String barFuga() {
    return null;
  }
}

画面表示例は以下の通り。

image.png

ちなみに、このタグは@Operationからも指定可能。

  @GetMapping("/foo/hoge")
  @Operation(tags = "異なるRestControllerのエンドポイントをタグでまとめる")
  public String fooHoge() {
    return null;
  }
build.gradle
plugins {
	id 'java'
	id 'org.springframework.boot' version '3.3.2'
	id 'io.spring.dependency-management' version '1.1.6'
}

group = 'com.example'
version = '0.0.1-SNAPSHOT'

java {
	toolchain {
		languageVersion = JavaLanguageVersion.of(17)
	}
}

configurations {
	compileOnly {
		extendsFrom annotationProcessor
	}
}

repositories {
	mavenCentral()
}

dependencies {
	implementation 'org.springframework.boot:spring-boot-starter-web'
	implementation 'org.springdoc:springdoc-openapi-starter-webmvc-ui:2.6.0'

	compileOnly 'org.projectlombok:lombok'
	annotationProcessor 'org.projectlombok:lombok'
	testImplementation 'org.springframework.boot:spring-boot-starter-test'
	testRuntimeOnly 'org.junit.platform:junit-platform-launcher'
}

tasks.named('test') {
	useJUnitPlatform()
}
0
0
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
0
0