[Spring Boot] Swagger 사용하기(Swagger3.0 , SpringBoot 3.0)

Posted by 김성철

SpringBoot - Swagger 3.0 버전 사용 (SpringBoot3.0)

SpringBoot 버전

id 'org.springframework.boot' version '3.0.5'  
id 'io.spring.dependency-management' version '1.1.0'  

사용이유

SpringBoot3.0으로 프로젝트를 시작하기로 함..  
그래서 일단 기본적인 설정부터 하자라고 마음먹고 Swagger 3.0을 세팅하기 시작함  
참고링크 :  
	※ 본인이 정리한 내용임..  

오류 발생

위에 정리한 내용대로 분명히 했음.  
근데 안됨 whitelabel error page 에러가뜸  
뭐가 문제지 싶어서 2.9.2 버전으로 내려봄  
참고링크 :  
	※ 본인이 정리한 내용임..  
  
뜨긴 하는데 스웨거에 접속하면 아래와 같이 메시지가 뜨면서 계속 리다이렉트됨  
======================================================================================================  
Unable to infer base url. This is common when using dynamic servlet registration or when the API  
is behind an API Gateway. The base url is the root of where all the swagger resources are served.  
======================================================================================================  

시도방법1(안됨) - 이전에 작성한 내용

1. 아래의 의존성 추가  
	======================================================================================================  
	implementation 'io.springfox:springfox-boot-starter:3.0.0'  
	======================================================================================================  
  
2. SwaggerConfig 파일 작성  
	======================================================================================================  
	package com.sungchul.recruiter.config;  
  
	import org.springframework.context.annotation.Bean;  
	import org.springframework.context.annotation.Configuration;  
	import springfox.documentation.builders.ApiInfoBuilder;  
	import springfox.documentation.builders.PathSelectors;  
	import springfox.documentation.builders.RequestHandlerSelectors;  
	import springfox.documentation.service.ApiInfo;  
	import springfox.documentation.service.Tag;  
	import springfox.documentation.spi.DocumentationType;  
	import springfox.documentation.spring.web.plugins.Docket;  
  
	@Configuration  
	public class SwaggerConfig {  
  
		@Bean  
		public Docket api() {  
			return new Docket(DocumentationType.OAS_30)  
					.tags(  
							new Tag("RecruiterController","Recruiter Manage Controller")  
					)  
					.useDefaultResponseMessages(false)  
					.select()  
					.apis(RequestHandlerSelectors.basePackage("com.sungchul.recruiter"))  
					.paths(PathSelectors.any())  
					.build()  
					.apiInfo(apiInfo());  
		}  
  
		private ApiInfo apiInfo() {  
			return new ApiInfoBuilder()  
					.title("Sungchul ETC Swagger")  
					.description("etc swagger config")  
					.version("1.0")  
					.build();  
		}  
	}  
	======================================================================================================  
  
3. 실행  
	whitelabel error page  

시도방법2(안됨) - @EnableSwagger2 추가

1. SwaggerConfig 상단에 @EnableSwagger2 어노테이션 추가  
  
2. 실행 자체에서 오류 발생  

시도방법3(안됨) - @EnableWebMvc 추가

1. SwaggerConfig 상단에 @EnableWebMvc 어노테이션 추가  
  
2. 애도 똑같이 오류남 - 오류메시지가 기억이 안남  

시도방법4(안됨) - Webconfig 정의

1. Webconfig.java 생성 후 아래와 같이 정의  
======================================================================================================  
package com.sungchul.recruiter.config;  
  
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;  
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;  
  
public class WebConfig implements WebMvcConfigurer {  
	@Override  
	public void addResourceHandlers(ResourceHandlerRegistry registry) {  
		registry.addResourceHandler("/swagger-ui/index.html")  
				.addResourceLocations("classpath:/META-INF/resources/");  
		registry.addResourceHandler("/webjars/**")  
				.addResourceLocations("classpath:/META-INF/resources/webjars/");  
	}  
}  
======================================================================================================  
  
2. 애도 오류남  
	whitelabel error page  

시도방법5(작동함) - springdoc-openapi-starter-webmvc-ui 로 갈아탐

공식문서URL : https://springdoc.org/  
			https://springdoc.org/v2/  
  
참고링크 : https://adjh54.tistory.com/72  
		https://recordsoflife.tistory.com/342  
		https://velog.io/@kjgi73k/Springboot3%EC%97%90-Swagger3%EC%A0%81%EC%9A%A9%ED%95%98%EA%B8%B0  
  
1. 지금까지 설정한 모든내용 삭제  
	1-1. SwaggerConfig.java , WebConfig.java 파일 삭제  
	1-2. implementation 'io.springfox:springfox-boot-starter:3.0.0' 의존성 삭제  
  
2.의존성 추가  
	의존성은 아래와 같이 springdoc-openapi-starter-webmvc-ui 를 추가해서 사용함.  
	springdoc:springdoc-openapi-ui만 사용하려면 SpringBoot의 버전을 낮춰야함, 시도방법6 참고  
  
	======================================================================================================  
	implementation 'org.springdoc:springdoc-openapi-starter-webmvc-ui:2.0.2'  
	======================================================================================================  
  
3. 접속  
	http://localhost:9090/swagger-ui/index.html##/  
	성공  
  
	별다른 설정파일 없이 스웨거에 접근이 가능해짐  
  
4. 설정  
	4-1. OpenAPIConfig.java 파일 생성  
		======================================================================================================  
		package com.sungchul.recruiter.config;  
  
		import io.swagger.v3.oas.models.Components;  
		import io.swagger.v3.oas.models.OpenAPI;  
		import io.swagger.v3.oas.models.info.Info;  
		import org.springframework.context.annotation.Bean;  
		import org.springframework.context.annotation.Configuration;  
  
		@Configuration  
		public class OpenAPIConfig {  
			@Bean  
			public OpenAPI openAPI() {  
				Info info = new Info()  
						.title("Recruiter API Document")  
						.version("v0.0.1")  
						.description("Recruiter API Document,");  
				return new OpenAPI()  
						.components(new Components())  
						.info(info);  
			}  
		}  
		======================================================================================================  
  
	4-2. application.yml 파일 설정  
		https://springdoc.org/##properties  
		======================================================================================================  
		spring:  
		  mvc:  
			pathmatch:  
			  matching-strategy: ant_path_matcher  
		server :  
		  port : 9090  
  
		springdoc:  
		  packages-to-scan: com.sungchul.recruiter  
		  default-consumes-media-type: application/json;charset=UTF-8  
		  default-produces-media-type: application/json;charset=UTF-8  
		  swagger-ui:  
			path: swagger-ui.html         ## Swagger UI 경로 , localhost:9090/swagger-ui/index.html default : swagger-ui/index.html  
			tags-sorter: alpha            ## alpha: 알파벳 순 태그 정렬, method: HTTP Method 순 정렬  
			operations-sorter: alpha      ## alpha: 알파벳 순 태그 정렬, method: HTTP Method 순 정렬  
		  api-docs:  
			path: /api-docs/json  
			groups:  
			  enabled: true  
		  cache:  
			disabled: true  
  
		======================================================================================================  

시도방법6(SpringBoot3미만 가능)

구글에서 검색하면 남들은 다 아래 라이브러리 하나로도 잘되는데 나는 안됨..  
다른점은 SpringBoot 버전이 다르다는것 뿐임.  
그래서 찾아본 결과 아래의 링크를 보면 SpringBoot3에서는 " springdoc-openapi-ui" 가 "springdoc-openapi-starter-webmvc-ui"로 변경되었다고 함  
	https://stackoverflow.com/questions/74701738/spring-boot-3-springdoc-openapi-ui-doesnt-work  
	"Please note that springdoc-openapi-ui now changed to springdoc-openapi-starter-webmvc-ui from spring boot 3."  
	"springdoc-openapi-ui는 springboot 3에서 springdoc-openapi-starter-webmvc-ui로 변경되었습니다."  
  
1. 의존성 추가  
	======================================================================================================  
	implementation 'org.springdoc:springdoc-openapi-ui:1.7.0'  
	======================================================================================================  
  
2. 설정파일은 시도방법5의 내용을 그대로 사용  
  
3. 실행  

springfox와 springdoc 비교

Github URL : https://github.com/springfox/springfox  
Github URL : https://github.com/springdoc/springdoc-openapi  
  
마지막 업데이트 :  
	springfox : 2020-10  
	springdoc : 2023-04-02  
webflux 지원 :  
	springfox : X  
	springdoc : O  
정렬기능 :  
	springfox : O  
	springdoc : X  

어노테이션 설명

@Tag  
	Controller에 대한 설명을 명시하는 어노테이션  
@Tag  
	속성 : name  
	API 그룹의 이름을 지정하는 속성  
@Tag  
	속성 : description  
	API 그룹의 설명을 지정하는 속성  
@Operation  
	API 그룹 내에 각각의 API를 명시하는 어노테이션  
@Operation  
	속성 : summary  
	API에 대한 간략한 설명을 지정하는 속성  
@Operation  
	속성 : description  
	API에 대한 상세 설명을 지정하는 속성  
@Operation  
	속성 : response  
	API에 대한 응답을 지정하는 속성  
@Operation  
	속성 : parameter  
	API에 대한 파라미터를 지정하는 속성  
@Schema  
	모델에 대한 설명을 명시하는 어노테이션  
@Schema  
	속성 : description  
	모델 자체 혹은 컬럼에 대한 설명을 하는 속성