[Spring] 3.x SpringDoc OpenAPI Swagger UI 설정

눈치없어·2024년 8월 28일

documentation를 작성하면서 Swagger를 사용하려는데

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

spring 3.x.x 버전부터는 springfox 라이브러리 호환이 안됨


삽질하고 검색하고 SpringDoc OpenAPI Starter WebMVC UI 라이브러리 사용함

implementation 'org.springdoc:springdoc-openapi-starter-webmvc-ui:2.0.2'

원래 있던 SwaggerConfig 파일은 OpenApiConfig로 바꿔버리고,

@Configuration
@OpenAPIDefinition(
        info = @Info(
                title = "날씨 일기 프로젝트",
                description = "날씨 일기를 CRUD 할 수 있는 백엔드 API 입니다.",
                version = "2.0.0"
        )
)
public class OpenApiConfig {

    @Bean
    public GroupedOpenApi publicApi() {
        return GroupedOpenApi.builder()
                .group("public")
                .pathsToMatch("/**")
                .build();
    }
}

코드는 대충 이렇게.



swagger-ui/index.html 기능이나 설명을 써보고 싶어서 controller 코드를 더럽혀봄
@Operation(
            summary = "일기 텍스트와 날짜를 이용해서 DB에 일기 저장합니다.",
            description = "이 API 엔드포인트는 주어진 날짜와 일기 텍스트를 사용하여 데이터베이스에 일기를 저장합니다.",
            parameters = {
                    @Parameter(
                            name = "date",
                            description = "저장할 일기의 날짜를 입력합니다. 형식: yyyy-MM-dd (예: 2024-08-28)",
                            example = "2024-08-28",
                            required = true,
                            schema = @Schema(type = "string", format = "date"))
            },
            requestBody = @io.swagger.v3.oas.annotations.parameters.RequestBody(
                    description = "일기 텍스트를 포함하는 요청 본문",
                    content = @Content(
                            schema = @Schema(
                                    type = "string",
                                    example = "오늘은 날씨가 좋다. 일기를 작성합니다."
                            )
                    )
            )
    )
    @PostMapping("/create/diary")
    public void createDiary(
            @RequestParam
            @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate date,
            @RequestBody String text) {
        diaryService.createDiary(date, text);
    }


이런식으로 crud 모두 하니깐 기존 코드가 두배가 됐음

spring 2.x 버전과 사용 방법이 다르지만 공식문서에 잘나와있음



공식문서 참고: https://springdoc.org/v2/

profile
dock 사이즈 다르잖아

0개의 댓글