对绝大多数程序员而言,写接口文档是一件痛苦的事情,相对文档,他们更愿意写代码。最理想的情况就是:代码即文档!服务开发完成后,部署上去文档就自动生成,没错,这就是springfox + swagger要解决的问题!
swagger号称 THE WORLD'S MOST POPULAR API TOOLING。但swagger默认情况下,仍要单独部署,程序员还是要跑到一个单独的web页面上编辑,写一堆yaml文档,依然不爽。
github上有一个springfox项目,可以在开发rest服务时,只要加一些注解,就自动生成swagger-ui界面,以及相关的文档,而且可以跟spring-boot/spring-cloud无缝集成。
步骤:
一、添加依赖项
dependencies { ... compile "io.springfox:springfox-swagger2:2.7.0" compile "io.springfox:springfox-swagger-ui:2.7.0" ... }
二、添加swagger配置类
1 package cn.mwee.order.cloud.service.express.config; 2 3 import org.springframework.context.annotation.Bean; 4 import org.springframework.context.annotation.Configuration; 5 import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; 6 import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; 7 import springfox.documentation.builders.ApiInfoBuilder; 8 import springfox.documentation.builders.PathSelectors; 9 import springfox.documentation.builders.RequestHandlerSelectors; 10 import springfox.documentation.service.ApiInfo; 11 import springfox.documentation.service.Contact; 12 import springfox.documentation.spi.DocumentationType; 13 import springfox.documentation.spring.web.plugins.Docket; 14 import springfox.documentation.swagger2.annotations.EnableSwagger2; 15 16 /** 17 * Created by yangjunming on 13/10/2017. 18 */ 19 @Configuration 20 @EnableSwagger2 21 public class SwaggerConfig { 22 23 @Bean 24 public Docket createRestApi() { 25 return new Docket(DocumentationType.SWAGGER_2) 26 .apiInfo(apiInfo()) 27 .select() 28 .apis(RequestHandlerSelectors.basePackage("xxx.controller")) //Controller所在的package 29 .paths(PathSelectors.any()) 30 .build(); 31 } 32 33 @Bean 34 public WebMvcConfigurerAdapter addResourceHandlers() { 35 return new WebMvcConfigurerAdapter() { 36 @Override 37 public void addResourceHandlers(ResourceHandlerRegistry registry) { 38 registry.addResourceHandler("swagger-ui.html") 39 .addResourceLocations("classpath:/META-INF/resources/"); 40 registry.addResourceHandler("/webjars/**") 41 .addResourceLocations("classpath:/META-INF/resources/webjars/"); 42 } 43 }; 44 } 45 46 private ApiInfo apiInfo() { 47 return new ApiInfoBuilder() 48 .title("express-service online api document") 49 .description("某某服务") 50 .contact(new Contact("作者名字", "http://
时间: 2024-12-31 02:57:31