swagger 3.x (boot)

Springfox swagger 3

이 문서에서는 Spring boot로 만든 REST API projectSpringfox swagger 3 설정을 통해 문서화하는 과정에 대해서 알아본다.

프로젝트 생성

프로젝트는 Spring Boot로 생성한다.

작성 시점(2022.01.28) 기준 Spring boot 2.6.x와 Springfox swagger 3는 호환이 되지 않는 이슈가 있다. 이를 해결하기 위해선 다음 두 가지 중 하나가 필요하다.

  1. SpringDoc 설정

  2. Spring boot 버전 변경(2.5.x)

의존성 설정

사용하는 빌드 도구에 맞게 의존성을 설정한다.

Maven (pom.xml)

<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-boot-starter</artifactId>
    <version>3.0.0</version>
</dependency>

Gradle (build.gradle)

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

프로젝트 설정

@Configuration을 생성하여 Swagger 설정을 수행한다.

@Configuration
public class SwaggerConfiguration {
	
	//문서 제작 도구를 bean으로 등록
	@Bean
	public Docket api() {
		return new Docket(DocumentationType.OAS_30)
		.useDefaultResponseMessages(false)
		.select()
		.apis(/*문서화 할 파일 범위*/)
		.paths(/*문서화 할 주소의 범위*/)
		.build()
		.apiInfo(info());
	}
	
	//정보 객체를 생성하는 메소드
	public ApiInfo info() {
		return new ApiInfoBuilder()
			.title("프로젝트 제목")
			.description("프로젝트 상세설명")
			.version("프로젝트 버전(x.y.z)")
			.license("프로젝트 라이선스")
			.build();
	}
	
}

DocumentationType은 버전에 맞게 준비된 상수를 사용하면 된다. 실제 코드를 보면 다음과 같이 작성되어 있다. Swagger 3에서는 DocumentationType.OAS_30을 사용한다.

public class DocumentationType extends SimplePluginMetadata {
  public static final DocumentationType SWAGGER_12 = new DocumentationType("swagger", "1.2");
  public static final DocumentationType SWAGGER_2 = new DocumentationType("swagger", "2.0");
  public static final DocumentationType OAS_30 = new DocumentationType("openApi", "3.0");
  //(생략) 
}

.apis()에서는 문서화 할 파일의 범위를 지정하며, 예를 들어 패키지로 지정할 경우 다음과 같이 작성한다.

.apis(RequestHandlerSelectors.basePackage("x.y.z"))

.paths()에서는 문서화 할 주소의 범위를 지정하며, 예를 들어 모든 주소를 허용할 경우 다음과 같이 작성한다.

.paths(PathSelectors.any())

설정을 작성한 후 애플리케이션을 실행하고 다음 주소로 들어가면 swagger ui가 출력된다.

  • swagger 2 - http://<host>:<port>/<context>/swagger-ui.html

  • swagger 3 - http://<host>:<port>/<context>/swagger-ui/index.html

Last updated