Springcloud 學習筆記07-Swagger2的詳細使用教程
阿新 • • 發佈:2021-08-23
1、Swagger2的功能
Swagger2是一個可以生成專案文件的工具,用來對專案的介面進行描述.是需要簡單的配置就可以立馬使用,並且還可以在自帶的前端介面進行函式的測試.
2、spring boot 整合Swgger2
引入相關的依賴:
<!-- 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> <!--引入ui包--> <dependency> <groupId>com.github.xiaoymin</groupId> <artifactId>swagger-bootstrap-ui</artifactId> <version>1.9.3</version> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-bean-validators</artifactId> <version>2.9.2</version> </dependency> <!--增加兩個配置解決NumberFormatException--> <dependency> <groupId>io.swagger</groupId> <artifactId>swagger-models</artifactId> <version>1.5.22</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-configuration-processor</artifactId> </dependency>
編寫配置類:
package com.ttbank.flep.file.config; import io.swagger.annotations.ApiOperation; 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.spi.DocumentationType; import springfox.documentation.spring.web.plugins.Docket; import springfox.documentation.swagger2.annotations.EnableSwagger2; @Configuration public class SwaggerConfig { @Bean public Docket createRestApi() { return new Docket(DocumentationType.SWAGGER_2) .apiInfo(apiInfo()) .select() // api掃包 .apis(RequestHandlerSelectors.basePackage("com.ttbank.flep.file.controller")) .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class)) .paths(PathSelectors.any()) .build(); } private ApiInfo apiInfo() { return new ApiInfoBuilder().title("Toov5|微服務電商系統").description("demo") .termsOfServiceUrl("http://www.itmayiedu.com") // .contact(contact) .version("1.0").build(); } }
特別注意:根據application.yml的相關配置,訪問對應的網址。
server.servlet.context-path為路徑字首,若yml中有相關設定,必須在url路徑中新增字首。
本案例訪問原生swagger2-ui的網址:http://localhost:7003/flep/file/swagger-ui.html
swagger-bootstrap-ui
是基於swagger介面api實現的一套UI,因swagger原生ui是上下結構的,在瀏覽介面時不是很清晰,所以,swagger-bootstrap-ui
是基於左右選單風格的方式,適用與我們在開發後臺系統左右結構這種風格類似,方便與介面瀏覽。
重點推薦swagger-bootstrap-ui的訪問方式:
http://127.0.0.1:7003/flep/file/doc.html
#application.yml為基本配置檔案 server: port: 7003 servlet: context-path: /flep/file #
swagger-ui效果圖為:
swagger-bootstrap-ui效果圖:
參考文獻:https://blog.csdn.net/qq_41291945/article/details/104544417