SpringBoot整合Swagger3生成接口文檔

 

先後端分離的項目,接口文檔的存在十分重要。與手動編寫接口文檔不一樣,swagger是一個自動生成接口文檔的工具,在需求不斷變動的環境下,手動編寫文檔的效率實在過低。與新版的swagger3相比swagger2配置更少,使用更加方便。php

1、pom文件中引入Swagger3依賴
<dependency>
     <groupId>io.springfox</groupId>
      <artifactId>springfox-boot-starter</artifactId>
      <version>3.0.0</version>
</dependency>

 

2、Application上面加入@EnableOpenApi註解html

 

@EnableOpenApi
@SpringBootApplication
@MapperScan(basePackages = {"cn.ruiyeclub.dao"})
public class Swagger3Application {
    public static void main(String[] args) {
        SpringApplication.run(Swagger3Application.class, args);
    }
}

 

3、Swagger3Config的配置spring

 

@Configuration
public class Swagger3Config {
    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.OAS_30)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
                .paths(PathSelectors.any())
                .build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("Swagger3接口文檔")
                .description("更多請諮詢服務開發者Ray。")
                .contact(new Contact("Ray。", "http://www.ruiyeclub.cn", "ruiyeclub@foxmail.com"))
                .version("1.0")
                .build();
    }
}
4、Swagger註解的使用說明
@Api:用在請求的類上,表示對類的說明
    tags="說明該類的做用,能夠在UI界面上看到的註解"
    value="該參數沒什麼意義,在UI界面上也看到,因此不須要配置"

@ApiOperation:用在請求的方法上,說明方法的用途、做用
    value="說明方法的用途、做用"
    notes="方法的備註說明"

@ApiImplicitParams:用在請求的方法上,表示一組參數說明
    @ApiImplicitParam:用在@ApiImplicitParams註解中,指定一個請求參數的各個方面
        name:參數名
        value:參數的漢字說明、解釋
        required:參數是否必須傳
        paramType:參數放在哪一個地方
            · header --> 請求參數的獲取:@RequestHeader
            · query --> 請求參數的獲取:@RequestParam
            · path(用於restful接口)--> 請求參數的獲取:@PathVariable
            · body(不經常使用)
            · form(不經常使用)
        dataType:參數類型,默認String,其它值dataType="Integer"       
        defaultValue:參數的默認值

@ApiResponses:用在請求的方法上,表示一組響應
    @ApiResponse:用在@ApiResponses中,通常用於表達一個錯誤的響應信息
        code:數字,例如400
        message:信息,例如"請求參數沒填好"
        response:拋出異常的類

@ApiModel:用於響應類上,表示一個返回響應數據的信息
            (這種通常用在post建立的時候,使用@RequestBody這樣的場景,
            請求參數沒法使用@ApiImplicitParam註解進行描述的時候)
    @ApiModelProperty:用在屬性上,描述響應類的屬性

 

 Controller層的配置:後端

watermark,size_16,text_QDUxQ1RP5Y2a5a6i,color_FFFFFF,t_100,g_se,x_10,y_10,shadow_90,type_ZmFuZ3poZW5naGVpdGk= View Codeapi

5、Swagger界面效果springboot

watermark,size_16,text_QDUxQ1RP5Y2a5a6i,color_FFFFFF,t_100,g_se,x_10,y_10,shadow_90,type_ZmFuZ3poZW5naGVpdGk=

 Swagger的訪問路徑由port/swagger-ui.html改爲了port/swagger-ui/ 或port/swagger-ui/index.html,項目演示代碼在springboot-swaggerrestful

 

 

watermark,size_16,text_QDUxQ1RP5Y2a5a6i,color_FFFFFF,t_100,g_se,x_10,y_10,shadow_90,type_ZmFuZ3poZW5naGVpdGk=

相關文章
相關標籤/搜索