Swagger 是一款RESTFUL接口的、基於YAML、JSON語言的文檔在線自動生成、代碼自動生成的工具。html
經過在controller中添加註解,便可輕易實現代碼文檔化。前端
Swagger提供ui界面,方便查看接口說明和測試接口功能。java
swagger-github git
本文主要講解如何建立一個swagger 的springboot starter項目,只要在其餘服務中引入該starter.並添加相關注解,便可完成接口文檔化。github
並講解了如何在spring cloud zuul網關中引入swagger,爲前端提供統一的訪問入口。web
本文的完整代碼:GitHub:swagger-starter。spring
<!-- swagger 依賴 --> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>2.9.2</version> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>2.9.2</version> </dependency>
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-configuration-processor</artifactId> <optional>true</optional> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <optional>true</optional> </dependency>
相關的配置屬性,將會在yml文件中進行配置api
package com.swagger.config; import lombok.Data; import org.springframework.boot.context.properties.ConfigurationProperties; @Data @ConfigurationProperties(prefix = "swagger") public class SwaggerProperties { //須要掃描的包路徑 private String basePackage = "com"; //顯示的標題 private String title = "swagger"; //聯繫人 private String contactName; //聯繫地址 private String contactUrl; //聯繫郵件地址 private String contactEmail; //文檔版本號 private String version; //描述 private String description; // private String termsOfServiceUrl; private String license; private String licenseUrl; }
配置類springboot
package com.swagger.config; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import springfox.documentation.builders.ApiInfoBuilder; import springfox.documentation.builders.PathSelectors; import springfox.documentation.builders.RequestHandlerSelectors; import springfox.documentation.service.ApiInfo; import springfox.documentation.service.Contact; import springfox.documentation.spi.DocumentationType; import springfox.documentation.spring.web.plugins.Docket; import springfox.documentation.swagger.web.UiConfiguration; /** *功能描述 * @author lgj * @Description swagger 配置類 * @date 6/5/19 */ @Slf4j @Configuration @EnableConfigurationProperties(SwaggerProperties.class) public class SwaggerConfig { @Autowired private SwaggerProperties swaggerProperties; @Bean public Docket docket() { return new Docket(DocumentationType.SWAGGER_2) .apiInfo(apiInfo()) .select() //爲當前包路徑 .apis(RequestHandlerSelectors.basePackage(swaggerProperties.getBasePackage())) .paths(PathSelectors.any()) .build(); } //構建 api文檔的詳細信息函數,注意這裏的註解引用的是哪一個 private ApiInfo apiInfo() { log.info("swaggerProperties = " + swaggerProperties); return new ApiInfoBuilder() //頁面標題 .title(swaggerProperties.getTitle()) //建立人 .contact(new Contact(swaggerProperties.getContactName(), swaggerProperties.getContactUrl(), swaggerProperties.getContactEmail())) //版本號 .version(swaggerProperties.getVersion()) //描述 .description(swaggerProperties.getDescription()) .license(swaggerProperties.getLicense()) .licenseUrl(swaggerProperties.getLicenseUrl()) .termsOfServiceUrl(swaggerProperties.getTermsOfServiceUrl()) .build() ; } @Bean UiConfiguration uiConfig() { return new UiConfiguration(null, "list", "alpha", "schema", UiConfiguration.Constants.DEFAULT_SUBMIT_METHODS, false, true, 60000L); } }
既然做爲starter,還須要指定項目啓動時的配置類,由於其餘項目引用時沒有指定掃描該類,那麼就不會建立相關的bean。app
所以須要在starter中指定。
在resource中建立文件 META-INF/spring.factories
spring.factories文件內容,經過EnableAutoConfiguration指定。
org.springframework.boot.autoconfigure.EnableAutoConfiguration=com.swagger.config.SwaggerConfig
swagger-springboot-starter建立完成。
<dependency> <groupId>com.swagger</groupId> <artifactId>swagger-springboot-starter</artifactId> <version>1.0.0</version> </dependency>
server:
port: 8900
swagger:
basePackage: com
title: "demo ui doc"
contactName: "libai"
contactUrl: contactUrl-demo
contactEmail: contactEmail-demo
version: v1.0.0
description: description-demo
termsOfServiceUrl: termsOfServiceUrl-demo
license: license-demo
licenseUrl: licenseUrl-demo
package com.demo.demo; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiParam; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.util.Date; @Api(value = "/demo",description = "demo controller") @RestController @RequestMapping("/demo") public class WebController { @ApiOperation(value = "/demo/1",notes="這是demo1",tags="{tag1,tag2}",response=String.class,httpMethod= "GET") @ApiParam(name = "name",value = "libai") @GetMapping("/1") public String demo1(String name){ return name + ":" + new Date().toString(); } @ApiOperation(value = "/demo/2",notes="這是demo2",tags="{tag3,tag4}",response=String.class,httpMethod= "POST") @PostMapping("/2") public String demo2(String name){ return name + ":" + new Date().toString(); } }
注意這裏使用@Api和@ApiOperation,@ApiParam等實現接口說明。
主要說明相關的類和方法。以便swagger-ui查看到。
更多使用方法參考本博文
@EnableSwagger2 @SpringBootApplication public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } }
啓動DemoApplication應用,訪問swagger-ui界面,地址http://localhost:8900/swagger-ui.html
能夠看到以前代碼中的相關配置。
同時,它還能夠實現對接口的測試
在使用spring cloud進行開發時,若是每一個微服務都引入sawgger,每一個微服務都是單獨的訪問地址,若是有幾百個微服務,對swagger進行管理訪問將會比較麻煩。所以須要在zuul網關提供統一的訪問入口。
<!-- swagger 依賴 --> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>2.9.2</version> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>2.9.2</version> </dependency> <!-- https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-starter-netflix-zuul --> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-zuul</artifactId> <version>2.1.0.RELEASE</version> </dependency>
server:
port: 8902 zuul: routes: #demo系統 demo: path: /demo/** url: http://localhost:8900
yml中配置的是demo應用的路由配置,當訪問 http://localhost:8902/demo/**/** 時,將會轉發到http://localhost:8900.也就是demo應用。
package com.zuul.demo.swagger; import org.springframework.context.annotation.Primary; import org.springframework.stereotype.Component; import springfox.documentation.swagger.web.SwaggerResource; import springfox.documentation.swagger.web.SwaggerResourcesProvider; import springfox.documentation.swagger2.annotations.EnableSwagger2; import java.util.ArrayList; import java.util.List; /** *功能描述 * @author lgj * @Description * @date 6/5/19 */ @EnableSwagger2 @Component @Primary public class SwaggerResources implements SwaggerResourcesProvider { @Override public List<SwaggerResource> get() { List resources = new ArrayList<>(); resources.add(swaggerResource("demo模塊", "/demo/v2/api-docs", "2.0")); return resources; } private SwaggerResource swaggerResource(String name, String location, String version) { SwaggerResource swaggerResource = new SwaggerResource(); swaggerResource.setName(name); swaggerResource.setLocation(location); swaggerResource.setSwaggerVersion(version); return swaggerResource; } }
swaggerResource("demo模塊", "/demo/v2/api-docs", "2.0")
注意這裏的location值,對應的是yml中的配置/demo + /v2/api-docs,可修改的是參數name。
demo: path: /demo/** url: http://localhost:8900
若是有新模塊須要添加
user-app: path: /user/** url: http://localhost:8903
只須要在這裏添加以下代碼便可。
resources.add(swaggerResource("user模塊", "/user/v2/api-docs", "2.0"));
package com.zuul.demo; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.netflix.zuul.EnableZuulProxy; @EnableZuulProxy @SpringBootApplication public class ZuulApplication { public static void main(String[] args) { SpringApplication.run(ZuulApplication.class, args); } }
啓動zuul應用,訪問地址:http://localhost:8902/swagger-ui.html
在右上角的"Select a spec"能夠選擇查看對應模塊的API文檔。
若是出現如下錯誤,則說明沒有添加註解@EnableSwagger2
完成!!!!!!!!!!!!!!