SpringFox에서 기본 파라미터 추가

예를 들어, contoller에는 정의하지 않지만 어플리케이션 고유의 header를 건네줄 필요가 있어, 그것을 swagger-ui로 표시하고 싶은 경우, Docket#globalRequestParameters 를 사용한다.

build.gradle
plugins {
  id 'org.springframework.boot' version '2.4.4'
  id 'io.spring.dependency-management' version '1.0.11.RELEASE'
  id 'java'
}

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

configurations {
  compileOnly {
    extendsFrom annotationProcessor
  }
}

repositories {
  mavenCentral()
}

dependencies {
  implementation 'org.springframework.boot:spring-boot-starter-web'
  compileOnly 'org.projectlombok:lombok'
  developmentOnly 'org.springframework.boot:spring-boot-devtools'
  annotationProcessor 'org.projectlombok:lombok'
  testImplementation 'org.springframework.boot:spring-boot-starter-test'

  implementation 'io.springfox:springfox-boot-starter:3.0.0'
}

test {
  useJUnitPlatform()
}
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import springfox.documentation.builders.ExampleBuilder;
import springfox.documentation.service.ParameterSpecification;
import springfox.documentation.service.ParameterType;
import springfox.documentation.service.RequestParameter;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;

@RestController
@SpringBootApplication
public class Application {
    @GetMapping("/hoge/{id}")
    public String hoge(@PathVariable String id) {
        return "hoge";
    }

    @PostMapping("/foo")
    public Foo foo(@RequestBody Foo foo) {
        return new Foo();
    }

    @Bean
    public Docket docket() {
        Docket docket = new Docket(DocumentationType.OAS_30);

        List<RequestParameter> parameters = new ArrayList<>();
        parameters.add(new RequestParameter(
                "name",
                ParameterType.HEADER,
                "description",
                false,
                false,
                false,
                new ParameterSpecification(null, null),
                new ExampleBuilder().id("id").build(),
                Collections.emptyList(),
                0,
                Collections.emptyList(),
                0));
        docket.globalRequestParameters(parameters);

        return docket;
    }

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

위와 같은 Docket의 bean을 작성하면 다음과 같은 화면 표시가 된다.

좋은 웹페이지 즐겨찾기