Spring swagger 사용법

HelloWorld·2023년 4월 9일

프로젝트를 진행하던 중, API를 정리한 문서가 필요해졌고 Swagger를 통해 API를 정리하기로 팀원과 결정하였다. 문제는... swagger 의존성이 주입되지 않고 계속 whiteLable Error가 발생했다는 점...

다른 프로젝트에서는 잘 진행되었는데 왜 이번 프로젝트에서는 에러가 나는지... 공식문서, Configuration, gradle, yml 등 설정 관련 파일들을 계속 만지다가 결국 알아낸 건,Spring 버전에 따라 gradle implement 가 다르다는 것...!

바로 공식문서와 코드로 알아보자.

진행 과정

아마 대부분 아래와 같은 의존성을 주입하고 있을 것이다. 많은 블로그에서 아래와 같이 설명하고 있고 관련 설정들도 알려주기 때문이다. 그런데 내 프로젝트에서는 진행이 안 된다? 스프링 버전을 한 번 살펴보자.

implementation 'org.springdoc:springdoc-openapi-ui:1.6.15

spring-docs/v1
위의 링크를 확인해보면

다음과 같은 문구를 확인 가능하다

스프링 v3이상을 사용중이라면
spring-docs/v2
위의 링크를 확인해보자


다음과 같은 라이브러리를 지원하고,

  • xml
   <dependency>
      <groupId>org.springdoc</groupId>
      <artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
      <version>2.1.0</version>
   </dependency>
  • gradle
implementation 'org.springdoc:springdoc-openapi-starter-webmvc-ui:2.1.0'

를 통해 사용 가능하다.

바꿔주면, 바로 Swagger 접속 가능!

Configuration

혹시나 관련 Config 파일이 궁금하실까봐,,,

import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.info.Info;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
@EnableWebMvc
public class SwaggerConfig implements WebMvcConfigurer {

    @Bean
    public OpenAPI OpenApi() {

        return new OpenAPI()
                .info(new Info().title("Test API")
                	.description("Test api 입니다.")
                    .version("v0.0.1"));
    }
}

spring-security

이거는 추가적인 내용인데, 우리 프로젝트에서는 로그인 관련하여 spring-security를 사용중이다.
이를 간과하고 swagger로 바로 접속하면 "Failed to load remote configuration"이라는 메시지가 뜨면서 내용을 볼 수 없다는 내용이 나온다.

이는 간단하게 해결 가능한데, spring-security 관련 config 파일에

.requestMatchers( "/","/swagger-ui/**", "/v3/api-docs/**").permitAll()

를 추가해주면 된다.


그럼 이만...!

0개의 댓글