프로그래밍/Java

Spring boot + swagger 예제

소행성왕자 2020. 12. 4. 11:38

Spring boot + swagger 예제 


본 포스팅은 swagger2를 통합하도록 스프링 부트 애플리케이션을 구성합니다.
스프링 부트 예제 는 REST API를 공개했습니다.
우리가 개발하는 REST 서비스의 문서화는 매우 중요합니다.
이 문서는 서비스 소비자가 사용 가능한 모든 서비스, 서명, 예상 입력을 알 수 있도록 도와줍니다.
또한 서비스가 작동하는지 테스트 할 수있는 간단한 방법이 있어야합니다.

노출 된 서비스는 변경 될 수 있으므로 동시에 문서도 업데이트 해야합니다.
이 작업을 수동으로 수행하면 특히 REST 서비스 수가 증가함에 따라 매우 지루한 프로세스가 됩니다.
문서화 프로세스를 자동화하는 데 도움이됩니다.

또한 API의 모든 변경 사항은 참조 문서에 동시에 설명되어야합니다.
이를 수동으로 수행하는 것은 지루한 작업이므로 프로세스 자동화가 불가피 했습니다.

Swagger는 무엇입니까

Swagger는 API 시각화에 널리 사용되며 Swagger UI를 통해 프런트 엔드 개발자에게 온라인 샌드 박스를 제공합니다.

튜토리얼에서는 Swagger 2 사양의 Springfox 구현을 사용합니다.
Swagger는 RESTful 웹 서비스의 시각적 표현을 생성하기위한 도구, 사양 및 완전한 프레임 워크 구현입니다.
이를 통해 서버와 동일한 속도로 문서를 업데이트 할 수 있습니다.
Swagger를 통해 적절하게 정의되면 소비자는 최소한의 구현 논리로 원격 서비스를 이해하고 상호 작용할 수 있습니다. 따라서 Swagger는 서비스를 호출 할 때 추측을 제거합니다.

프로젝트는 다음과 같습니다.
Maven 에서 우리는 swagger 의존성이 필요합니다.

 

<?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">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.4.0</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.swagger</groupId>
    <artifactId>demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>swagger</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

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

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.4.0</version>
        </dependency>

        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.4.0</version>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>
package com.swagger.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class SwaggerApplication {

    public static void main(String[] args) {
        SpringApplication.run(SwaggerApplication.class, args);
    }

}
package com.swagger.demo;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloController {

    @RequestMapping(method = RequestMethod.GET, value="/api/javainuse")
    public String sayHello() {
        return "Swagger Hello World!";
    }
}
package com.swagger.demo;

import com.google.common.base.Predicate;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
import static springfox.documentation.builders.PathSelectors.regex;
import static com.google.common.base.Predicates.or;

@Configuration
@EnableSwagger2
public class SwaggerConfig {

    public Docket postsApi() {
        return new Docket(DocumentationType.SWAGGER_2).groupName("public-api")
                .apiInfo(apiInfo()).select().paths(postPaths()).build();
    }

    private Predicate<String> postPaths() {
        return or(regex("/api/posts.*"), regex("/api/javainuse.*"));
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder().title("JavaInUser API")
                .description("JavaInUser API reference fo developers")
                .termsOfServiceUrl("http://daum.net")
                .contact("asdf@asdf.com").license("Naya License")
                .licenseUrl("asdf@asdf.com").version("1.0").build();
    }
}

http://localhost:8080/swagger-ui.html  접속해봅시다.