[Java] 在Gradle project 中加入Swagger

Swagger 是一套 Web API 管理工具, 除了一般測試外, 還可以當成API 的user menu. 而Swagger 亦已經有library 使整合變得更方便. 示範中會將swagger 整合到spring RESTful API 中.

  1. 加入dependency.
    在API project 中內的 build.gradle 加入以下dependencies.

    dependencies {
       // Add Swagger.
       compile("io.springfox:springfox-swagger2:2.7.0")
       compile("io.springfox:springfox-swagger-ui:2.7.0")
    }
  2. 設定swagger.
    於project 中建立java 檔, 命名為SwaggerConfig.java, 並輸入以下代碼:

    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.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)  
              .select()                                  
              .apis(RequestHandlerSelectors.any())              
              .paths(PathSelectors.any())                          
              .build();                                           
        }
    }
  3. 設定與Spring 的整合.
    於project 中建立java 檔, 命名為SwaggerWebMvcConfigurationAdapter.java, 並輸入以下代碼:

    import org.springframework.web.servlet.config.annotation.EnableWebMvc;
    import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
    import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
    
    @SuppressWarnings("deprecation")
    @EnableWebMvc
    public class SwaggerWebMvcConfigurationAdapter 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/");
    	}
    }
  4. 進行測試.
    執行Project, 並於瀏覽器輸入以下網址. 若見到swagger 網頁顯示, 代表測試成功.

    http://localhost:8080/swagger-ui.html

About C.H. Ling 262 Articles
a .net / Java developer from Hong Kong and currently located in United Kingdom. Thanks for Google because it solve many technical problems so I build this blog as return. Besides coding and trying advance technology, hiking and traveling is other favorite to me, so I will write down something what I see and what I feel during it. Happy reading!!!

Be the first to comment

Leave a Reply

Your email address will not be published.


*


This site uses Akismet to reduce spam. Learn how your comment data is processed.