[swagger] in springboot2.6.2 and springdoc
초기 환경: swagger 2.9.2, springboot 2.6.2
@Configuration
@EnableSwagger2
@RequiredArgsConstructor
public class SwaggerConfig {
private final TypeResolver typeResolver;
@Bean
public Docket restAPI() {
return new Docket(DocumentationType.SWAGGER_2)
.alternateTypeRules(AlternateTypeRules.newRule(
typeResolver.resolve(Pageable.class),
typeResolver.resolve(SwaggerPage.class)))
.apiInfo(apiInfo())
.directModelSubstitute(LocalDateTime.class, String.class)
.select()
.apis(RequestHandlerSelectors.basePackage("package.controller"))
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("test_backend")
.version("1.0.0")
.description("This is swagger!")
.build();
}
@Getter
@Setter
@ApiModel
public static class SwaggerPage {
@ApiParam(example = "1", defaultValue = "1")
@ApiModelProperty(value = "페이지 번호(1~N)")
private int page;
@ApiParam(example = "20", defaultValue = "20")
@ApiModelProperty(value = "페이지 크기", allowableValues = "range[0, 100]")
private int size;
@ApiModelProperty(value = "정렬(사용법: 컬럼명,ASC|DESC)")
private List<String> sort;
}
}
위 빈 설정이 springboot2.5.6에서는 잘 작동하였는데, 부트 버전을 2.6.2로 올리고 나서 부터는 아래와 같은 에러가 발생한다.
org.springframework.context.ApplicationContextException: Failed to start bean 'documentationPluginsBootstrapper'; nested exception is java.lang.NullPointerException
방안 1) 찾아보니 springboot2.6.x 대와 설정 값이 맞지 않는 부분(해답2에 언급)이 있기 때문이며 boot 버전을 2.5.x로 내리면 된다.
방안 2) 부트2.6.2에서 아래 설정 값을 추가하니 잘 실행되었다. 아래 값은 부트2.5.x에서는 기본값이었는데 2.6.x로 오면서 기본값이 바뀌었고 아래 값으로 변경 값을 override 해주면 된다.
spring.mvc.pathmatch.matching-strategy=ANT_PATH_MATCHER
허나 스프링 진영에서 이 default값을 변경하게 된 이유가 있을 터, 이 설정값이 어떤 이슈를 가져올지 모르므로 단순히 설정 값 변경으로 해결하고 싶지 않았다.
방안 3) 스웨거 변경 springfox -> springdoc
springfox가 2.9 버전 이후로 한동안 업데이트를 안 하다가 2년 만에 2.10, 3.0 버전을 만들었는데, 그 사이 springdoc 진영에서 새로 만든 swagger가 요새 뜨고 있는 듯하다.
https://www.libhunt.com/compare-springfox-vs-springdoc-openapi?ref=compare
springfox vs springdoc-openapi - compare differences and reviews? | LibHunt
springfox Posts with mentions or reviews of springfox. We have used some of these posts to build our list of alternatives and similar projects. The last one was on 2020-12-22.
www.libhunt.com
springdoc이 더 다양한 옵션(보안 관련/ webclient 비동기 등)을 먼저 지원하여 빠른 안정화를 하고 있고, 설정만으로도 금세 만들 수 있다는 장점, 스프링에서 밀어주는 느낌, springfox의 게으름 및 버그 등등의 이유로 springdoc의 스웨거를 사용해보고자 한다.
심지어 springdoc에서는 springfox에서 어떻게 바꿀 수 있는지 가이드도 해준다..ㅋㅋ
https://springdoc.org/#migrating-from-springfox
OpenAPI 3 Library for spring-boot
Library for OpenAPI 3 with spring boot projects. Is based on swagger-ui, to display the OpenAPI description.Generates automatically the OpenAPI file.
springdoc.org
위 설정대로 진행하니 기본적인 화면은 잘 나온다. 허나 나는 pageable 내용이 swagger에 나오는 걸 중시해서(페이징 테스트를 스웨거로 하고 싶다) 샘플 api를 작성했는데 자꾸 오브젝트로 나오는 것이었다..?!
implementation "org.springdoc:springdoc-openapi-data-rest:${swaggerVersion}"
위 dependency 넣으면 된다고 글에 쓰여있었는데.. 그래도 안돼서 더 찾아봤더니
@ParameterObject
위 어노테이션을 변수에 넣어야 한다고 한다.. 기본값을 주려면 @PageableDefault랑 같이 쓰면 된다. 아래처럼 말이다.
@GetMapping("game")
@Operation(description = "게임기록조회(일반/토너먼트)")
public BaseResponse<Page<?>> gameLogByTypeAndGid(@ParameterObject @PageableDefault(size = 20, sort = "seq", direction = Sort.Direction.DESC) Pageable pageable){
return new BaseResponse<>();
}
게다가 1.6.4 버전부터는 org.springdoc:springdoc-openapi-data-rest 의존성도 필요 없다(코어에 포함시켰다고 한다)고 하니 완전 땡큐다. 바로 지우고 실행했는데 아래와 같이 잘 나온다.
추가사항.. POST 요청 시 request body를 위 사진처럼 input 타입으로 주고 싶은데 지원이 안 되는 것 같다. GET / query param만 저렇게 가능한 듯하다... 이러면 직접 json을 손대야 해서 실수가 날까 봐 별로 안 좋아하는데,, 이 때문에 springfox로 돌아가야 하나 살짝 고민된다.
참고
나랑 같은 고민을 한 사람들: https://stackoverflow.com/questions/70178343/springfox-3-0-0-is-not-working-with-spring-boot-2-6-0
Springfox 3.0.0 is not working with Spring Boot 2.6.0
Springfox 3.0.0 is not working with Spring Boot 2.6.0, after upgrading I am getting the following error org.springframework.context.ApplicationContextException: Failed to start bean '
stackoverflow.com
openapi 적용 법: https://www.baeldung.com/spring-rest-openapi-documentation
migration, jwt: https://deepak-shinde.medium.com/migrating-from-springfox-swagger-2-to-springdoc-openapi-3-79a79757b8d1
Migrating from Springfox Swagger 2 to Springdoc OpenAPI 3
As we know documentation is an essential part of building REST APIs. I have been using Springfox for my Spring boot projects for quite a…
deepak-shinde.medium.com
springdoc pageable included in 1.6.4
https://github.com/springdoc/springdoc-openapi/issues/1415
Moving PageableDefault support to springdoc-openapi-common · Issue #1415 · springdoc/springdoc-openapi
Describe the bug Pageable is documented to be used with Parameter(hidden) and PageableAsQueryParam. When we add PageableDefault, the default page size should be 10 but is reported as 20. To Reprodu...
github.com