溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

Spring boot配置 swagger的代碼怎么寫

發(fā)布時間:2021-09-24 15:26:50 來源:億速云 閱讀:166 作者:柒染 欄目:開發(fā)技術

Spring boot配置 swagger的代碼怎么寫,針對這個問題,這篇文章詳細介紹了相對應的分析和解答,希望可以幫助更多想解決這個問題的小伙伴找到更簡單易行的方法。

為什么使用Swagger

    在實際開發(fā)中我們作為后端總是給前端或者其他系統(tǒng)提供接口,每次寫完代碼之后不可避免的都需要去寫接口文檔,首先寫接口文檔是一件繁瑣的事,其次由接口到接口文檔需要對字段、甚至是排版等。再加上如果我們是為多個系統(tǒng)提供接口時可能還需要按照不同系統(tǒng)的要求去書寫文檔,那么有沒有一種方式讓我們在開發(fā)階段就給前端提供好接口文檔,甚至我們可以把生成好的接口文檔暴露出去供其他系統(tǒng)調(diào)用,那么這樣我只需要一份代碼即可。

Spring boot配置 swagger

 1.導入maven依賴

<!--配置swagger-->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.6.1</version>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.6.1</version>
        </dependency>

        <!--swagger第三方ui-->
        <dependency>
            <groupId>com.github.xiaoymin</groupId>
            <artifactId>swagger-bootstrap-ui</artifactId>
            <version>1.9.6</version>
        </dependency>

2.swagger配置類

@EnableSwagger2                // Swagger的開關,表示已經(jīng)啟用Swagger
@Configuration                 // 聲明當前配置類
public class SwaggerConfiguration  {

    @Value("${swagger.basePackage}")
    private String basePackage;       // controller接口所在的包

    @Value("${swagger.title}")
    private String title;           // 當前文檔的標題

    @Value("${swagger.description}")
    private String description;         // 當前文檔的詳細描述

    @Value("${swagger.version}")
    private String version;         // 當前文檔的版本



    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage(basePackage))
                .paths(PathSelectors.any())
                .build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title(title)
                .description(description)
                .version(version)
                .build();
    }

}

3.application.yml

# 配置swagger
swagger:
  basePackage: com.xx.demo.controller #包名
  title: 標題  #標題
  description: 項目文檔 #描述
  version: V1.0  #版本號

4.在controller里使用

@Api(tags = {"測試類"})
@RestController
@RequestMapping("/test")
public class TestController {
    @ApiOperation(value = "測試方法")
    @GetMapping("/xrx")
    public String xrx() {
        return "hello";
    }
}

5.訪問swagger

http://localhost:8080/swagger-ui.html
http://localhost:8080/doc.html

Spring boot配置 swagger的代碼怎么寫

關于Spring boot配置 swagger的代碼怎么寫問題的解答就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,如果你還有很多疑惑沒有解開,可以關注億速云行業(yè)資訊頻道了解更多相關知識。

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權內(nèi)容。

AI