log

[Springboot] swagger 적용 및 발생 오류 정리 본문

SpringBoot

[Springboot] swagger 적용 및 발생 오류 정리

sun_young 2023. 9. 20. 00:55

1. 환경 설정

build.gradle 파일에 추가

implementation group: 'io.springfox', name: 'springfox-swagger-ui', version: '2.9.2'
implementation group: 'io.springfox', name: 'springfox-swagger2', version: '2.9.2'

 

2. SwaggerConfig 파일 생성

@Configuration
@EnableSwagger2
public class SwaggerConfig {

    @Bean
    public Docket api() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .securityContexts(Arrays.asList(securityContext()))
                .securitySchemes(Arrays.asList(apiKey()))
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.example.everytime"))
                .paths(PathSelectors.any())
                .build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("everytime Spring Boot REST API")
                .version("1.0.0")
                .description("에브리타임 클론 코딩 프로젝트 swagger api")
                .build();
    }

    private SecurityContext securityContext() {
        return SecurityContext.builder()
                .securityReferences(defaultAuth())
                .build();
    }

    private List<SecurityReference> defaultAuth() {
        AuthorizationScope authorizationScope = new AuthorizationScope("global", "accessEverything");
        AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];
        authorizationScopes[0] = authorizationScope;
        return Arrays.asList(new SecurityReference("Authorization", authorizationScopes));
    }

    private ApiKey apiKey() {
        return new ApiKey("Authorization", "Authorization", "header");
    }
}

① apiInfo : API에 대한 정보

② securityContexts, securitySchemes : security가 적용된 프로젝트를 swagger에도 적용시키기 위함

(이 부분은 더 공부가 필요함ㅜ)

- SecurityContext : 인증 방식

- apiKey : swagger내에 인증하는 방식

③ apis : 패키지 설정

④ paths : 문서화를 위한 경로 지정 (위 코드에서는 모든 경로를 문서화한다)

 

 

🚨 Failed to start bean 'documentationPluginsBootstrapper' 오류 발생

정확한 원인은 모르겠으나 구글링해보니 Spring boot 2.6 버전 이후 spring.mvc.pathmatch.matching-strategy 값이 ant_path_matcher에서 path_pattern_parser로 변경되면서 오류가 발생하고 있다고 한다

 

 

🔎 해결 방법

application.properties 파일에 아래 코드를 추가한다

spring.mvc.pathmatch.matching-strategy=ant_path_matcher