Swagger 是一套 Web API 管理工具, 除了一般測試外, 還可以當成API 的user menu. 而Swagger 亦已經有library 使整合變得更方便. 示範中會將swagger 整合到spring RESTful API 中.
- 加入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") }
- 設定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(); } }
- 設定與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/"); } }
- 進行測試.
執行Project, 並於瀏覽器輸入以下網址. 若見到swagger 網頁顯示, 代表測試成功.http://localhost:8080/swagger-ui.html
Leave a Reply