관리 메뉴

나만의공간

Spring Boot Project Initializr (Swagger 연결) #3 본문

IT/Spring

Spring Boot Project Initializr (Swagger 연결) #3

밥알이 2022. 1. 3. 10:26

연재순서

1. Spring Boot Project Initializr (스프링 부트 프로젝트 생성법)
2. Spring Boot Project Initializr (RestFul API 연결)
3. Spring Boot Project Initialzr (Swagger 연결)  
4. Spring Boot Project Initializr (Log4j 연결)
5. Spring Boot Project Initializr (Requet Get/Post 출력)
6. 번외 : Spring Boot War 파일 생성, 로컬 Tomcat 뛰우기
7.  Srping Boot Project Initializr (GitHub 위치) 

Spring Boot 기본설정을 완료 했습니다.
Spring Boot를 이용하여 API 호출을 하고 호출된 API결과를 웹 브라우져에 정상 적으로 노출 되는것도 확인 했습니다.
이제 API 가이드 문서를 쉽게 만들고 테스트 할 수 있는 Swagger를 연동 해 보겠습니다.
Gradle 설정에 추가 하고 몇가지만 설정 하면 금방 적용 됩니다.
Swagger 가이드 : https://swagger.io/

Swagger import 설정

build.gradle 파일에 아래 Swagger 설정을 추가 합니다.
springfox-swagger2 3.0.0 / springfox-swagger-ui 두개를 추가 후 Gradle설정을 Import 합니다.

dependencies {
   implementation 'org.springframework.boot:spring-boot-starter-web'
   compileOnly 'org.projectlombok:lombok'
   annotationProcessor 'org.projectlombok:lombok'
   testImplementation 'org.springframework.boot:spring-boot-starter-test'
   implementation group: 'io.springfox', name: 'springfox-swagger2', version: '3.0.0'
   implementation group: 'io.springfox', name: 'springfox-swagger-ui', version: '3.0.0'
}

Swagger Config Class 파일을 만듭니다.

Swagger Config같은 설정파일을 모아놓을 Package를 먼저 만듭니다.
-. core라는 Package명으로 만듭니다.


해당 Package에 SwaggerConfig.java 클래스 파일을 아래와 같이 만듭니다.

package com.study.studyTwo.core;

import io.swagger.annotations.ApiOperation;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@Configuration
@EnableSwagger2
public class SwaggerConfig {

    @Bean
    public Docket api() {
        return new Docket(DocumentationType.SWAGGER_2)
            .groupName("studyTwo")
            .select()
            .apis(RequestHandlerSelectors.basePackage("com.study.studyTwo"))
            .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
            .paths(PathSelectors.any())
            .build()
            .apiInfo(this.apiInfo());
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
            .title("studyTwo")
            .description("REST API")
            .version("1.0")
            .build();
    }
}

메인 도메인 접속시 Swagger 화면이 바로 노출 될 수 있도록 이전에 설정했던 Root(메인)에 대한 설정이 있을경우 주석 처리를 한다.
application.properties 파일 주석 처리

#server.servlet.context-path=/study

Swagger UI설정을위한 Servlet파일 생성

core Package에 ServletConfig 파일을 추가로 생성한다.

package com.study.studyTwo.core;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * servlet context 설정을 위한 config
 */
@Configuration
public class ServletConfig implements WebMvcConfigurer {

    private static final String[] CLASSPATH_PATH_PATTERNS = {"swagger-ui.html", "/webjars/**"};
    private static final String[] CLASSPATH_RESOURCE_LOCATIONS = {"classpath:/META-INF/resources/",
        "classpath:/META-INF/resources/webjars/"};

    /**
     * mvc:resources 설정을 처리합니다.
     *
     * @param registry {@link ResourceHandlerRegistry} 클래스
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler(CLASSPATH_PATH_PATTERNS).addResourceLocations(CLASSPATH_RESOURCE_LOCATIONS);
//        registry.addResourceHandler("swagger-ui.html") .addResourceLocations("classpath:/META-INF/resources/");
//        registry.addResourceHandler("/webjars/**") .addResourceLocations("classpath:/META-INF/resources/webjars/");

    }

    /**
     * ROOT(/) path 진입시 /swagger-ui.html 쪽으로 리다이렉트 처리합니다.
     *
     * @param registry {@link ViewControllerRegistry} 클래스
     */
    @Override
    public void addViewControllers(final ViewControllerRegistry registry) {
        registry.addViewController("/").setViewName("redirect:/swagger-ui.html");
    }
}

 

Swagger 오류 발생시 조치 사항

우리가 https://start.spring.io/ 에서 받은 Spring Boot설정파일에 Spring boot 버전이 2.6.2이 경우 Swagger연결시 아래와 같은 오류가 발생할 수 있다.
이 경우 Spring boot 2.5.2로 변경하면 된다.
Swagger 오류 : Failed to start bean 'documentationPluginsBootstrapper'

Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2022-01-03 10:13:38.393 ERROR 3826 --- [           main] o.s.boot.SpringApplication               : Application run failed

org.springframework.context.ApplicationContextException: Failed to start bean 'documentationPluginsBootstrapper'; nested exception is java.lang.NullPointerException
	at org.springframework.context.support.DefaultLifecycleProcessor.doStart(DefaultLifecycleProcessor.java:181) ~[spring-context-5.3.14.jar:5.3.14]
	at org.springframework.context.support.DefaultLifecycleProcessor.access$200(DefaultLifecycleProcessor.java:54) ~[spring-context-5.3.14.jar:5.3.14]
	at org.springframework.context.support.DefaultLifecycleProcessor$LifecycleGroup.start(DefaultLifecycleProcessor.java:356) ~[spring-context-5.3.14.jar:5.3.14]
	at java.base/java.lang.Iterable.forEach(Iterable.java:75) ~[na:na]
	at org.springframework.context.support.DefaultLifecycleProcessor.startBeans(DefaultLifecycleProcessor.java:155) ~[spring-context-5.3.14.jar:5.3.14]
	at org.springframework.context.support.DefaultLifecycleProcessor.onRefresh(DefaultLifecycleProcessor.java:123) ~[spring-context-5.3.14.jar:5.3.14]
	at org.springframework.context.support.AbstractApplicationContext.finishRefresh(AbstractApplicationContext.java:935) ~[spring-context-5.3.14.jar:5.3.14]

2022/1/3일 Swagger gradle 최신 버전이 3.0으로 제공되는데 3.0을 사용할 경우 
Whitelabel Error Page 가 나올수 있어 Swagger Version 2.9.2로 변경한다.

아래는 build.gradle 변경한 최종 파일 내용입니다.

plugins {
// id 'org.springframework.boot' version '2.6.2'
   id 'org.springframework.boot' version '2.5.2'
   id 'io.spring.dependency-management' version '1.0.11.RELEASE'
   id 'java'
}

group = 'com.study'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '11'

configurations {
   compileOnly {
      extendsFrom annotationProcessor
   }
}

repositories {
   mavenCentral()
}

dependencies {
   implementation 'org.springframework.boot:spring-boot-starter-web'
   compileOnly 'org.projectlombok:lombok'
   annotationProcessor 'org.projectlombok:lombok'
   testImplementation 'org.springframework.boot:spring-boot-starter-test'
   implementation group: 'io.springfox', name: 'springfox-swagger2', version: '2.9.2'
   implementation group: 'io.springfox', name: 'springfox-swagger-ui', version: '2.9.2'
// implementation group: 'io.springfox', name: 'springfox-swagger2', version: '3.0.0'
// implementation group: 'io.springfox', name: 'springfox-swagger-ui', version: '3.0.0'
}

test {
   useJUnitPlatform()
}

 

Swagger 설정 완료 화면

위 설정대로 모든것이 완료되면 서버를 실행해서 localhost:8080으로 접속하면 Swagger 화면이 로컬에 노출됩니다.

 

다음 연재는 Get / Post로 넘어온 Request정보를 출력 하는 예제를 만들어 보기로 하겠습니다.

 

Comments