給項目添加swagger


1.什么是swagger

官方介紹Swagger是一個規范且完整的框架,提供描述、生產、消費和可視化RESTful Web Service。
專業角度:Swagger是由龐大工具集合支撐的形式化規范。這個集合涵蓋了從終端用戶接口、底層代碼庫到商業API管理的方方面面。

2.為什么要用swagger

作為一個很懶的碼代碼的猿呢,對於一些API的理解總是很模糊不清,但是,總想着能直接驗證一下自己的理解就好了,而不是需要去項目寫測試代碼來驗證自己的想法。所以說,API文檔應該有直接運行的能力。而Swagger就是這樣的一個東西,它可以為已有項目的生成具備執行能力的樣式化API文檔,這樣可以極大的方便程序員對前端后台進行對接整合。

3.開發環境:

JDK:1.8

swagger:2.6.0

gradle依賴:

compile(
"io.springfox:springfox-swagger2:2.6.1",
"io.springfox:springfox-swagger-ui:2.6.1"
)

4.swagger配置類

通過注解將配置了注入spring

 1 package com.zhoulei.config;
 2 
 3 
 4 import org.springframework.context.annotation.Bean;
 5 import org.springframework.context.annotation.Configuration;
 6 import org.springframework.web.servlet.config.annotation.EnableWebMvc;
 7 import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
 8 import springfox.documentation.builders.ApiInfoBuilder;
 9 import springfox.documentation.builders.PathSelectors;
10 import springfox.documentation.builders.RequestHandlerSelectors;
11 import springfox.documentation.service.ApiInfo;
12 import springfox.documentation.service.Contact;
13 import springfox.documentation.spi.DocumentationType;
14 import springfox.documentation.spring.web.plugins.Docket;
15 import springfox.documentation.swagger2.annotations.EnableSwagger2;
16 
17 /**
18  * @author: lzhou
19  * @date: 2018/09/07 14:09
20  * @version: V1.0
21  */
22 @Configuration
23 //@EnableWebMvc
24 @EnableSwagger2
25 public class SwaggerConfig{
26     @Bean
27     public Docket createRestApi() {
28         return new Docket(DocumentationType.SWAGGER_2)
29                 .apiInfo(apiInfo())
30                 .select()
31                 .apis(RequestHandlerSelectors.basePackage("com.zhoulei.controller"))
32                 .paths(PathSelectors.any())
33                 .build();
34     }
35 
36     private ApiInfo apiInfo() {
37         return new ApiInfoBuilder()
38                 .title("Springboot測試項目")
39                 .description("如有調用問題請發送郵箱:384701202@qq.com")
40                 .contact(new Contact("EP-lzhou","http://www.baidu.com","384701202@qq.com"))
41                 .version("1.0")
42                 .build();
43     }
44 
45 }

5.編寫control類進行測試

@ResponseBody
    @RequestMapping(value = "/test", method = RequestMethod.POST)
    @ApiOperation(value ="Springboot測試接口" ,notes = "Springboot測試接口")
    public String Test(@RequestBody String info){
        return info;
    }

6.運行項目,輸入地址:http://localhost:9099/swagger-ui.html#!(自己的地址和端口)效果如下:

 
       


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM