[SpringBoot] Swagger 작성

Yoona Di·2024년 10월 15일

Spring Boot

목록 보기
4/4
post-thumbnail

결국 멀티모듈을 포기하고 일단 자바 프로젝트로 다시 생성했다..
멀티모듈만 잡고 있기엔 계속 시간을 낭비할 것 같아서 😥 나중에 어느정도 구현하고 멀티모듈에 대해 따로 알아봐야겠다.

인텔리제이에서 java gradle로 새로운 프로젝트를 생성해주었다.
🔽 이 부분은 앞 블로그를 참고하자
spring boot 프로젝트 생성 참고

스웨거(Swagger) 연결

스웨거란
-> 간단히 말해서 API 문서를 자동으로 만들어주는 라이브러리다.

스웨거는 UI가 짜여있고 코드를 바꿀때마다 바로바로 바뀌니 notion이나 excel같이 직접 작성하는 것보다 편하다.

1. build.gradle

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

먼저 라이브러리를 추가해줘야한다.

2. SwaggerConfig.java

public class SwaggerConfig {

    @Bean
    public OpenAPI openAPI() {

        Info info = new Info()
                .version("v1.0.0")
                .title("peep Todo API")
                .description("peep TODO API 명세입니다.");

        return new OpenAPI()
                .info(info);
    }
}

새로운 SwaggerConfig라는 클래스를 생성해준다.

 @Operation(summary = "회원가입", description = "유저저장")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "신규유저를 생성합니다.",content = @Content(mediaType = "application/json")),
            @ApiResponse(responseCode = "404", description = "요청한 리소스를 찾을 수 없습니다.",content = @Content(mediaType = "application/json", schema = @Schema(implementation = Error.class))),
            @ApiResponse(responseCode = "500", description = "서버 오류가 발생했습니다..",content = @Content(mediaType = "application/json", schema = @Schema(implementation = Error.class)))
    })

Media Type란
-> request, response body data의 형식이다.

  • media type들은 content 필드 아래에 작성한다.

우리는 application/json을 사용한다.
-> 이 형식의 데이터는 json 형식으로 되어 있다는 의미

Q. 사실 schema랑 mediaType 둘 다 작성해줘야하는지는 아직 잘 모르겠다.

스웨거 문제점

편하기만 한 것이 아닌것이 하나의 api를 작성할때마다 저 스웨거 코드를 하나씩 다 붙여줘야하는 번거로움이 생긴다.

그럼 이걸 어떻게 해결할거냐..

우리에게는 custom annotation이라는 좋은 도구가 있다.

custom annotation

1. 200(Success)

@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Operation()
@ApiResponses(value = {
        @ApiResponse(
                responseCode = "200",
                description = "",
                content = @Content(mediaType = "application/json")
        )
})
public @interface SwaggerApiSuccess {
    String summary() default "";
    String description();
}

@Target : 어노테이션이 적용될 수 있는 대상을 정의할 수 있는 어노테이션.

  • @Target({ElementType.METHOD}) : 메서드에 붙일 수 있다는 의미.

@Retentation : ('유지'라는 뜻) 어노테이션을 언제까지 유지할 것인지를 정의하는 부분.

  • @Retention(RetentionPolicy.RUNTIME) : 컴파일러에 의해 .class 파일에 기록되고, JVM에 의해서 어노테이션이 유지된다. = Java로 작성한 코드가 돌아가는 동안엔 계속 유지된다.

2. 404(conflictError)

@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Operation()
@ApiResponses(value = {
        @ApiResponse(
                responseCode = "404",
                description = "요청한 리소스를 찾을 수 없습니다.",
                content = @Content(
                        mediaType = "application/json",
                        schema = @Schema(implementation = Error.class)))
})
public @interface SwaggerApiNotFoundError {
}

3. 500(internetServerError)

@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Operation()
@ApiResponses(value =
    @ApiResponse(
            responseCode = "500",
            description = "서버 오류가 발생했습니다..",
            content = @Content(
                    mediaType = "application/json",
                    schema = @Schema(implementation = Error.class)))
)
public @interface SwaggerInternetServerError {
}

이렇게 하면 Swagger코드를 이렇게만 작성해도 작동이 된다!

@SwaggerApiSuccess(summary = "회원가입", description = "신규유저를 생성합니다.")
@SwaggerApiNotFoundError
@SwaggerInternetServerError

참고 자료
[Spring] 커스텀 Annotation 만들기
[Spring Boot] Swagger의 비즈니스 코드 개입 최소화하기

profile
개발자가 되고싶은 초보

0개의 댓글