Spring Boot에 Swagger를 적용하기 위해서 다음의 dependency를 POM에 추가합니다. JSP를 렌더링 해야 하므로 JSP Container도 추가합니다.

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">

    ....
    
    <properties>
        <java.version>1.8</java.version>
        <maven.compiler.version>3.8.1</maven.compiler.version>

        <spring.boot.version>2.4.1</spring.boot.version>
        <swagger.version>3.0.0</swagger.version>
    </properties>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <version>${spring.boot.version}</version>
                <configuration>
                    <executable>true</executable>
                </configuration>
            </plugin>

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>${maven.compiler.version}</version>
                <configuration>
                    <source>${java.version}</source>
                    <target>${java.version}</target>
                    <encoding>UTF-8</encoding>
                </configuration>
            </plugin>
        </plugins>
    </build>

    <dependencies>
        <!-- ============================= -->
        <!--  Spring Framework Dependency  -->
        <!-- ============================= -->

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        ....

        <!-- =================== -->
        <!--  Tomcat Dependency  -->
        <!-- =================== -->

        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.tomcat.embed</groupId>
            <artifactId>tomcat-embed-jasper</artifactId>
        </dependency>

        <!-- ==================== -->
        <!--  Swagger Dependency  -->
        <!-- ==================== -->

        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-boot-starter</artifactId>
            <version>${swagger.version}</version>
        </dependency>
    </dependencies>

    <!-- ======================= -->
    <!--  Dependency Management  -->
    <!-- ======================= -->

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-dependencies</artifactId>
                <version>${spring.boot.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>
</project>

Spring Boot의 Configuration을 생성합니다.

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

import java.util.ArrayList;

@Configuration
@EnableSwagger2
public class SwaggerConfiguration {

    @Bean
    public Docket api() {
        return new Docket(DocumentationType.SWAGGER_2)
                .select()
                .apis(RequestHandlerSelectors.any())
                .paths(PathSelectors.ant("/services/**/*"))
                .build()
                .apiInfo(apiInfo());
    }

    private ApiInfo apiInfo() {
        return new ApiInfo(
                "API 명",
                "API 상세 설명",
                "1.0.0",
                "www.data-dynamics.io",
                new Contact("Contact Me", "www.example.com", "foo@example.com"),
                "Licenses",
                "www.example.com",
                new ArrayList<>());
    }

}

WebMVC 설정에서 Swagger에 접근할 수 있도록 추가합니다.

import com.amazonaws.HttpMethod;
import com.lgdisplay.bigdata.api.iam.logging.AuthLoggingInterceptor;
import com.lgdisplay.bigdata.api.iam.util.CollectionUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.config.annotation.*;
import org.springframework.web.servlet.view.InternalResourceViewResolver;

@Slf4j
@Configuration
public class WebMvcConfiguration implements WebMvcConfigurer {

    private final String baseUrl;

    public WebMvcConfiguration(@Value("${springfox.documentation.swagger-ui.base-url:}") String baseUrl) {
        this.baseUrl = baseUrl;
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        String baseUrl = StringUtils.trimTrailingCharacter(this.baseUrl, '/');

        // Swagger UI를 표시하기 위한 리소스를 설정한다.
        registry.addResourceHandler(baseUrl + "/swagger-ui/**")
                .addResourceLocations("classpath:/META-INF/resources/webjars/springfox-swagger-ui/")
                .resourceChain(false);
    }

    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        // /로 접근하면 Swagger UI로 리다이렉트한다.
        registry.addRedirectViewController("/", "/swagger-ui/");
    }

    @Override
    public void configureViewResolvers(ViewResolverRegistry registry) {
        // Internal View Resolver가 추가되어 있지 않으면 Swagger 화면이 표시되지 않는다.
        registry.viewResolver(new InternalResourceViewResolver());
    }

}

이제 Boot를 실행하고 http://locahost:8080/ 로 접근하며 Swagger가 실행됩니다.

1 Comment

  1. Edward

    초간단 버전입니다.

    Maven Dependency 추가

    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-boot-starter</artifactId>
        <version>3.0.0</version>
    </dependency>

    Swagger Configuration 설정

    Spring Boot Configuration을 위해서 다음과 같이 Configuration 클래스를 추가합니다.

    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.web.bind.annotation.RequestMethod;
    import springfox.documentation.builders.PathSelectors;
    import springfox.documentation.builders.RequestHandlerSelectors;
    import springfox.documentation.builders.ResponseMessageBuilder;
    import springfox.documentation.schema.ModelRef;
    import springfox.documentation.service.ApiInfo;
    import springfox.documentation.service.Contact;
    import springfox.documentation.service.ResponseMessage;
    import springfox.documentation.spi.DocumentationType;
    import springfox.documentation.spring.web.plugins.Docket;
    import springfox.documentation.swagger2.annotations.EnableSwagger2;
    
    import java.util.ArrayList;
    import java.util.List;
    
    /**
     * Swagger을 초기화하는 Spring Boot Configuration.
     */
    @Configuration
    @EnableSwagger2
    public class SwaggerConfiguration {
    
        @Bean
        public Docket api() {
    
            List<ResponseMessage> responseMessages = new ArrayList<ResponseMessage>();
            responseMessages.add(new ResponseMessageBuilder().code(200).message("OK").build());
            responseMessages.add(new ResponseMessageBuilder().code(500).message("서버 에러").responseModel(new ModelRef("Error")).build());
            responseMessages.add(new ResponseMessageBuilder().code(404).message("페이지를 찾을 수 없습니다").build());
    
            return new Docket(DocumentationType.SWAGGER_2)
                    .select()
                    .apis(RequestHandlerSelectors.any())
                    .paths(PathSelectors.ant("/api/**/*"))
                    .build()
                    .apiInfo(apiInfo())
                    .useDefaultResponseMessages(false)
                    .globalResponseMessage(RequestMethod.GET, responseMessages);
    
        }
    
        private ApiInfo apiInfo() {
            return new ApiInfo(
                    "Cloudera Manager Alarm Service API",
                    "Cloudera Manager Alarm Service API",
                    "1.0.0",
                    "www.data-dynamics.io",
                    new Contact("Contact Me", "www.data-dynamics.io", "admin@data-dynamics.io"),
                    "Licenses",
                    "www.data-dynamics.io",
                    new ArrayList<>());
        }
    
    }

    WebMVC 설정

    Swagger를 실행하기 위한 최소의 WebMVC 설정입니다. /로 진입하는 경우 /swaggger-ui로 redirect하여 UI가 표시됩니다. /는 프로젝트 환경에 맞춰서 변경하도록 합니다.

    import lombok.extern.slf4j.Slf4j;
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.http.HttpMethod;
    import org.springframework.util.StringUtils;
    import org.springframework.web.servlet.config.annotation.*;
    import org.springframework.web.servlet.view.InternalResourceViewResolver;
    
    @Slf4j
    @Configuration
    public class WebMvcConfiguration implements WebMvcConfigurer {
        private final String baseUrl;
    
        public WebMvcConfiguration(@Value("${springfox.documentation.swagger-ui.base-url:}") String baseUrl) {
            this.baseUrl = baseUrl;
        }
    
        @Override
        public void addResourceHandlers(ResourceHandlerRegistry registry) {
            String baseUrl = StringUtils.trimTrailingCharacter(this.baseUrl, '/');
    
            // Swagger UI를 표시하기 위한 리소스를 설정한다.
            registry.addResourceHandler(baseUrl + "/swagger-ui/**")
                    .addResourceLocations("classpath:/META-INF/resources/webjars/springfox-swagger-ui/")
                    .resourceChain(false);
        }
    
        @Override
        public void addViewControllers(ViewControllerRegistry registry) {
            // /로 접근하면 Swagger UI로 리다이렉트한다.
            registry.addRedirectViewController("/", "/swagger-ui/");
        }
    
        @Override
        public void configureViewResolvers(ViewResolverRegistry registry) {
            // Internal View Resolver가 추가되어 있지 않으면 Swagger 화면이 표시되지 않는다.
            registry.viewResolver(new InternalResourceViewResolver());
        }
       }
    }