Programing

Spring MVC 애플리케이션에서 Swagger를 구현하는 '간단한'방법

lottogame 2020. 10. 8. 07:40
반응형

Spring MVC 애플리케이션에서 Swagger를 구현하는 '간단한'방법


간단한 Spring으로 작성된 ReSTFul API가 있습니다 (Spring Boot 없음, 멋진 물건 없음!). 여기에 Swagger를 구현해야합니다. 지금까지 인터넷의 모든 페이지는 이식성이 전혀없는 혼란스러운 구성과 부풀어 오른 코드로 나를 미치게 만들었습니다.

이 작업을 수행하는 데 도움이되는 샘플 프로젝트 (또는 일련의 세부 단계)가 있습니까? 특히 swagger-springmvc를 사용하는 좋은 샘플을 찾고 있습니다. 나는 그것이 '샘플'을 가지고 있음을 알고 있지만 기껏해야 난해한 코드는 낙담합니다.

나는 "Swagger가 단순히 최고인 이유"를 찾고 있지 않음을 분명히해야합니다. 나는 Spring Boot 등을 사용하지 않습니다 (현재 작업에는 사용하지 않을 것입니다).


Springfox (Swagger 사양 2.0, 현재)

Springfox 는 Swagger-SpringMVC를 대체했으며 이제 Swagger 사양 1.2 및 2.0을 모두 지원합니다. 구현 클래스가 변경되어 좀 더 심층적 인 사용자 정의가 가능하지만 약간의 작업이 필요합니다. 문서 개선,하지만 여전히 고급 구성을 위해 추가 된 몇 가지 세부 사항을해야합니다. 1.2 구현에 대한 이전 답변은 여전히 ​​아래에서 찾을 수 있습니다.

Maven 종속성

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

최소한의 구현은 거의 비슷해 보이지만 이제는 Docket클래스 대신 클래스를 사용합니다 SwaggerSpringMvcPlugin.

@Configuration
@EnableSwagger2
public class SwaggerConfig {

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

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
            .title("TITLE")
            .description("DESCRIPTION")
            .version("VERSION")
            .termsOfServiceUrl("http://terms-of-services.url")
            .license("LICENSE")
            .licenseUrl("http://url-to-license.com")
            .build();
    }

}

Swagger 2.0 API 문서는 이제에서 사용할 수 있습니다 http://myapp/v2/api-docs.

참고 : Spring 부트를 사용하지 않는 경우 jackson-databind 종속성을 추가해야합니다. springfox는 데이터 바인딩에 jackson을 사용하기 때문에.

이제 Swagger UI 지원을 추가하는 것이 훨씬 더 쉽습니다. Maven을 사용하는 경우 Swagger UI webjar에 다음 종속성을 추가하십시오.

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

Spring Boot를 사용하는 경우 웹 앱이 자동으로 필요한 파일을 선택하고 http://myapp/swagger-ui.html(이전 :)에 UI를 표시해야합니다 http://myapp/springfox. Spring Boot를 사용하지 않는 경우 yuriy-tumakha가 아래 답변에서 언급했듯이 파일에 대한 리소스 핸들러를 등록해야합니다. Java 구성은 다음과 같습니다.

@Configuration
@EnableWebMvc
public class WebAppConfig extends WebMvcConfigurerAdapter {

    @Override 
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
    }

}

새로운 정적 문서 생성 기능도 꽤 멋져 보이지만 직접 시도하지는 않았습니다.

Swagger-SpringMVC (Swagger 사양 1.2 이전)

Swagger-SpringMVC에 대한 문서는 약간 혼란 스러울 수 있지만 실제로 설정하는 것은 매우 쉽습니다. 가장 간단한 구성은 SpringSwaggerConfig빈을 생성하고 주석 기반 구성을 활성화 해야 합니다 (아마도 Spring MVC 프로젝트에서 이미 수행 한 작업).

<mvc:annotation-driven/>
<bean class="com.mangofactory.swagger.configuration.SpringSwaggerConfig" />

그러나 SwaggerSpringMvcPlugin이전 XML 정의 빈 대신를 사용하여 사용자 지정 Swagger 구성을 정의하는 추가 단계를 수행하는 것이 가치가 있다고 생각합니다 .

@Configuration
@EnableSwagger
@EnableWebMvc
public class SwaggerConfig {

    private SpringSwaggerConfig springSwaggerConfig;

    @SuppressWarnings("SpringJavaAutowiringInspection")
    @Autowired
    public void setSpringSwaggerConfig(SpringSwaggerConfig springSwaggerConfig) {
        this.springSwaggerConfig = springSwaggerConfig;
    }

    @Bean
    public SwaggerSpringMvcPlugin customImplementation(){

        return new SwaggerSpringMvcPlugin(this.springSwaggerConfig)
                .apiInfo(apiInfo())
                .includePatterns(".*api.*"); // assuming the API lives at something like http://myapp/api
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
            .title("TITLE")
            .description("DESCRIPTION")
            .version("VERSION")
            .termsOfServiceUrl("http://terms-of-services.url")
            .license("LICENSE")
            .licenseUrl("http://url-to-license.com")
            .build();
    }

}

애플리케이션을 실행할 때 이제에서 생성 된 API 사양을 볼 수 있습니다 http://myapp/api-docs. 멋진 Swagger UI를 설정하려면 GitHub 프로젝트 에서 정적 파일을 복제하여 프로젝트 에 넣어야합니다. 프로젝트가 정적 HTML 파일을 제공하도록 구성되었는지 확인합니다.

<mvc:resources mapping="*.html" location="/" />

Then edit the index.html file at the top level of the Swagger UI dist directory. Towards the top of the file, you'll see some JavaScript that refers to the api-docs URL of another project. Edit this to point to your project's Swagger documentation:

  if (url && url.length > 1) {
    url = url[1];
  } else {
    url = "http://myapp/api-docs";
  }

Now when you navigate to http://myapp/path/to/swagger/index.html, you should see the Swagger UI instance for your project.


Springfox Swagger UI works for me after adding WebJar dependency and resource mappings. http://www.webjars.org/documentation#springmvc

    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger2</artifactId>
        <version>2.2.2</version>
    </dependency>
    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger-ui</artifactId>
        <version>2.2.2</version>
    </dependency>
    <dependency>
        <groupId>org.webjars</groupId>
        <artifactId>bootstrap</artifactId>
        <version>3.3.5</version>
    </dependency>

spring-servlet.xml:

<mvc:resources mapping="swagger-ui.html" location="classpath:/META-INF/resources/"/>
<mvc:resources mapping="/webjars/**" location="classpath:/META-INF/resources/webjars/"/>

or Spring Annotation https://github.com/springfox/springfox-demos/blob/master/spring-java-swagger/src/main/java/springfoxdemo/java/swagger/SpringConfig.java

Swagger2 should be enabled

 @EnableSwagger2
 public class SwaggerConfiguration {
 }

You can also consider using swagger-maven-plugin to generate swagger.json and copy it to yours static swagger-ui.

Please check simple sample of working plugin with Spring MVC annotations on this repo:

https://github.com/khipis/swagger-maven-example

or for JAX-RS

https://github.com/kongchen/swagger-maven-example

참고URL : https://stackoverflow.com/questions/26720090/a-simple-way-to-implement-swagger-in-a-spring-mvc-application

반응형