[Spring] Swagger

양정훈·2022년 6월 16일

Swagger UI

  • API 리소스 문서 자동 생성

springfox-swagger-ui

  • Spring 환경에서 Swagger UI를 세팅해주는 라이브러리
  • 접속 URL : {{path}}/swagger-ui/index.html

환경

  • Spring Boot 2.7.0
  • springfox-boot-starter 3.0.0
  • springfox:springfox-swagger-ui 3.0.0

사용

  • build.gradle
dependencies {
    implementation 'io.springfox:springfox-boot-starter:3.0.0'
    implementation 'io.springfox:springfox-swagger-ui:3.0.0'
}
  • application.yml
    Spring Boot 2.6부터 PATH_PATTERN_PARSER가 기본 값이 되어서 호환이 되지 않음. 아래와 같이 설정 변경이 필요함
spring.mvc.pathmatch.matching-strategy: ANT_PATH_MATCHER
  • SwaggerConfiguration.java
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
//import springfox.documentation.swagger2.annotations.EnableSwagger2;

//@EnableSwagger2 // Swagger 3.x 부터 불필요
@Configuration
public class SwaggerConfiguration {

    @Bean
    public Docket api() {
        return new Docket(DocumentationType.SWAGGER_2) // Swagger 2 사용
            // 기본 응답코드들 (200, 401, 403 ...) 에 대한 기본 메세지 사용 여부
            .useDefaultResponseMessages(false)
            .select()
            .apis(RequestHandlerSelectors.any())
            .paths(PathSelectors.any())
            .build()
            .apiInfo(new ApiInfo(
                "Title",
                "Description",
                "1.0",
                "Term of service URL",
                new Contact("Contact name", "Contact URL", "Contact email"),
                "License",
                "License URL",
                Collections.emptyList()
            ));
    }
}

springdoc을 쓰자

  • springfox의 마지막 업데이트는 20년 7월이고 이후 업데이트가 되지 않고 있음
  • 위의 PATH_PATTERN_PARSER 호환 문제도 그래서 발생하는게 아닌가 싶음 (PATH_PATTERN_PARSER 가 SpringBoot 기본 설정이 된게 21년 11월로 (boot 2.6), springfox 마지막 업데이트 이후임)

springdoc-openapi-ui

사용

  • build.gradle
dependencies {
    implementation group: 'org.springdoc', name: 'springdoc-openapi-ui', version: '1.6.9'
}
  • application.yml
# 문서 접속 URL 변경 (접속시 /swagger-ui/index.html 로 redirect됨)
springdoc.swagger-ui.path: /api-document.html

# 캐시 비활성화 (Swagger 구성 요소중 캐시로 처리되는 부분이 있음, 로컬 환경에서만 사용하는 것이 좋을듯)
springdoc.cache.disabled: true

# 모든 @ControllerAdvice 응답이 모든 api의 응답으로 추가됨 (모든 응답에 추가되므로, 해당 response가 일어나지 않는 api에도 추가가 됨. false로 설정)
springdoc.override-with-generic-response: false
  • controller.py
@RestController
@RequestMapping("/members")
@Tag(name = "/members", description = "사용자")
public class MemberController {

	@GetMapping("/{id}")
    @Operation(summary = "사용자 조회", description = "사용자 번호로 사용자 조회")
    public Object getById(
    	@Parameter(
        	name = "번호",
            // DEFAULT, HEADER, QUERY, PATH, COOKIE
            in = ParameterIn.PATH,
            description = "사용자 번호", 
            required = true,
            example = "1"
        )
        @PathVariable("id") Long id
    ) {}
}

0개의 댓글