본문 바로가기
Java

Spring Boot 3 Swagger 설정

by parkjp 2023. 9. 5.

 

Dependency 설치

Spring Boot 3.x 기준 Swagger를 설정해 보겠다.

implementation group: 'org.springdoc', name: 'springdoc-openapi-starter-webmvc-ui', version: '2.1.0'

필자는 springdoc-openapi-starter-webmvc-ui 2.1 버전을 설치하였다.

2.0 이상 버전을 설치하길 바란다.

 

 

Swagger 설정

기본적인 설정을 해보겠다. title이나 버전은 각자 맞춰서 하면 된다.

@Configuration
@RequiredArgsConstructor
public class SwaggerConfig {

    @Value("${server.version}")
    private String ServerVersion;
    @Value("${spring.config.activate.on-profile}")
    private String springProfile;

    @Bean
    public OpenAPI api() {
        return new OpenAPI()
                .info(this.apiInfo())
                ;
    }

    private Info apiInfo() {
        return new Info()
                .title("[" + springProfile + "] " + "Api Server ")
                .version(ServerVersion)
                ;
    }
}

 

 

 

Swagger 사용법

일단 swagger는 두 가지 사용법이 존재하는데 하나는 yaml파일로 관리, 하나는 Controller 메소드 쪽에서 관리하는 법이다.

필자는 각 컨트롤러 메소드에서 바로바로 볼 수 있는 것이 관리하기 편하고, 사실상 로직은 서비스에서 작성되니 보기 편한  Controller 메소드 쪽에서 작성하는 법을 예시로 보여주겠다.

 

    @Tag(name = "Auth")
    @Operation(method = "POST", description = "예시", parameters = {
            @Parameter(in = ParameterIn.HEADER, name = "headerParam", description = "~~", required = true, schema = @Schema(implementation = Long.class)),
            @Parameter(in = ParameterIn.COOKIE, name = "CookieParam", description = "~~", required = true, schema = @Schema(implementation = String.class))
    })
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "OK", content = @Content(schema = @Schema(implementation = DTO.class))),
            @ApiResponse(responseCode = "500", description = "ERROR")
    })
    @RequestMapping(value = "/example", method = RequestMethod.POST)
    public ResponseEntity<DTO> example(@RequestBody @Valid ExampleRequest request) {
        return ResponseEntity.ok(this.service.example(request));
    }

 

 

  • @Tag: tag 어노테이션은 같은 태그를 달린 컨트롤러 메소드를 그룹화하는 역할을 한다. 예를 들어, 로그인과 회원가입 API를 Auth라는 태그로 묶어두면 swagger 페이지에서 같은 그룹으로 묶여 표현된다.
  • @Operation: operation 어노테이션은 이 메소드의 설명이나 파라미터 설정, Content-type 설정, HttpMethod 설정같은 부분을 할 수 있다.
  • @ApiResponses: apiResponses 어노테이션은 응답에 따른 status 값에 대한 설명, Response DTO에 관한 설정을 할 수 있다.

 

자 그럼 Request DTO 설정은 어디서 하는건가?

컨트롤러 쪽에 헤더나 쿠키 이외에는 컨트롤러 메소드가 받은 DTO 객체에 @Schema를 설정한다.

위 예시의 ExampleRequest 객체를 살펴보자.

@Setter
@Getter
@Schema(description = "~~")
public class ExampleRequest {
    @Schema(description = "~~")
    private Long example1;
    @Schema(description = "~~")
    private Integer example2;
}

 

보다시피 @Schema를 적용하면 Swagger Schema에 등록이 되어 Swagger ui에서도 표현이 가능하게 된다.

반응형