Spring Swagger 적용법
- Spring boot 3.2.1, SpringDoc 2.0.2 버전 사용
// build.gradle
swaggerimplementation 'org.springdoc:springdoc-openapi-starter-webmvc-ui:2.0.2'
- application.yaml - swagger 설정 파일 추가 시
springdoc:
swagger-ui:
# swagger-ui 접근 경로. default 값은 /swagger-ui.html이다.
path: /swagger-custom-ui.html
# 각 API의 그룹 표시 순서
# path, query, body, response 순으로 출력
groups-order: DESC
# 태그 정렬 순서.
# alpha: 알파벳 순 정렬
# method: OpenAPI specification file에 원하는 태그 정렬 방식 직접 기재
tags-sorter: alpha
# 컨트롤러 정렬 순서.
# method는 delete - get - patch - post - put 순으로 정렬된다.
# alpha를 사용해 알파벳 순으로 정렬할 수 있다.
operations-sorter: method
# swagger-ui default url인 petstore html의 비활성화 설정
disable-swagger-default-url: true
# swagger-ui에서 try 했을 때 request duration을 알려주는 설정
display-request-duration: true
# openAPI 접근 경로. default 값은 /v3/api-docs 이다.
api-docs:
path: /api-docs
# Spring Actuator의 endpoint까지 보여줄 것인지?
show-actuator: true
# request media type 의 기본 값
default-consumes-media-type: application/json
# response media type 의 기본 값
default-produces-media-type: application/json
# 해당 패턴에 매칭되는 controller만 swagger-ui에 노출한다.
paths-to-match:
- /api/**
- 인증 관련 필터에 걸리지 않도록 처리
// JwtFilter
@Override
protected boolean shouldNotFilter(HttpServletRequest request) throws ServletException {
String path = request.getRequestURI();
String[] excludePath = {"/swagger-ui", "/api-docs", "/webjars", "/swagger-resources",
"/error", "/login", "/api/user/signup", "/logout", "/favicon.ico"}; // "/api/user/refresh",
return Arrays.stream(excludePath).anyMatch(path::startsWith);
}
Swagger Example
@Operation(summary = "신호 잔여 시간 조회", description = "교차로ID를 통해 신호 잔여 시간을 조회합니다. pageNo, pageSize 기본값이 0, 1입니다.")
@ApiResponses(value = {
@ApiResponse(responseCode = "200", description = "success",
content = @Content(schema = @Schema(implementation = LightFeignMetaResponse.class))),
@ApiResponse(responseCode = "400", description = "교차로ID(itsId)가 잘못되었을 때 timeout 에러가 발생합니다.",
content = @Content(schema = @Schema(implementation = CommonResponse.class)))
})
@GetMapping("")
public ResponseEntity<Object> getLightTimingFeign(
@RequestParam(name = "itstId") String itstId,
@RequestParam(name = "pageNo", defaultValue = "1") String pageNo,
@RequestParam(name = "pageSize", defaultValue = "1") String pageSize
) {
LightRequest lightRequest = new LightRequest(itstId, pageNo, pageSize);
return readLightUsecase.execute(lightRequest);
}
- @Operation : API 참조 summary / description 명시
- @ApiResponses : @ApiResponse들을 명시한다.
- @ApiResponse: httpCode와 어떤 상황에 해당 응답이 오는지 설명
- @Content 타입에 Response class를 명시할 수 있다.

Share article