一步步學(xué)習java后臺(六)(OpenApi-Swagger的使用)

OpenApi(Swagger)

OpenApi,以前稱為Swagger ,是最受歡迎的API文檔規(guī)范之一。
它允許您使用JSON或YAML元數(shù)據(jù)描述API的屬性。它還提供了一個Web UI,它可以將元數(shù)據(jù)轉(zhuǎn)換為一個很好的HTML文檔。

SpringFox

SpringFox提供了自動生成Swagger-UI的組件。它可以自動檢查您的類,檢測控制器,它們的方法,它們使用的模型類以及它們映射到的URL。沒有任何手寫文檔,只需檢查應(yīng)用程序中的類,它就可以生成大量有關(guān)API的信息。

在Spring Boot工程中添加 Swagger2

springfox-swagger2 2.x.x版本

1.在pom文件中添加Swagger2依賴

        <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>
  1. 創(chuàng)建Swagger2配置類

在在Application.java同級創(chuàng)建Swagger2的配置類Swagger2。

image.png
@Configuration
@EnableSwagger2
public class Swagger2 {
    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .paths(PathSelectors.any())
                .build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("Spring Boot 初始化學(xué)習工程")
                .version("1.0")
                .build();
    }
}

通過@Configuration注解,讓Spring來加載該類配置。再通過@EnableSwagger2注解來啟用Swagger2。

再通過createRestApi函數(shù)創(chuàng)建Docket的Bean之后,apiInfo()用來創(chuàng)建該Api的基本信息(這些基本信息會展現(xiàn)在文檔頁面中)。select()函數(shù)返回一個ApiSelectorBuilder實例用來控制哪些接口暴露給Swagger來展現(xiàn),本例采用指定掃描的包路徑來定義,Swagger會掃描該包下所有Controller定義的API,并產(chǎn)生文檔內(nèi)容(除了被@ApiIgnore指定的請求)。

訪問如下地址就可以訪問 Swagger
http://localhost:8080/swagger-ui.html#/

git地址:
tag: 1-swaggur-2.x

springfox 3.x.x版本

2020年6月 Springfox 發(fā)布了3.0.0版本,進一步簡化了配置。

.在pom文件中添加OpenApi啟動器

 <groupId>io.springfox</groupId>
    <artifactId>springfox-boot-starter</artifactId>
    <version>3.0.0</version>
</dependency>

在Application上添加注解

@EnableOpenApi

image.png

配置類可加可不加

訪問地址變更為:
http://localhost:8080/swagger-ui/index.html#/

OpenApi注解

image.png

雖然不加任何注解,生成的UI頁面也可以提供接口,參數(shù)等等信息,但是我們還是希望可以獲取更加人性化的提示。通過注解 @ApiOperation@ApiImplicitParam就可以做到。

    @ApiOperation(value="創(chuàng)建用戶", notes="根據(jù)User對象創(chuàng)建用戶")
    @PostMapping("/")
    public String postUser(@RequestBody User user) {
        // @RequestBody注解用來綁定通過http請求中application/json類型上傳的數(shù)據(jù)
        users.put(user.getId(), user);
        return "success";
    }

    @ApiOperation(value="獲取用戶詳細信息", notes="根據(jù)url的id來獲取用戶詳細信息")
    @ApiImplicitParam(name = "id", value = "用戶ID", required = true, dataType = "Long", example = "0")
    @GetMapping("/{id}")
    public User getUser(@PathVariable Long id) {
        // url中的id可通過@PathVariable綁定到函數(shù)的參數(shù)中
        return users.get(id);
    }
image.png
遇到的報錯
  1. 工程無法運行起來

報錯:

Parameter 0 of method linkDiscoverers in org.springframework.hateoas.config.HateoasConfiguration required a single bean, but 15 were found:

資料1中使用的pom maven版本號為 2.0.2 導(dǎo)致

  1. 打開Swagger頁面時報錯
java.lang.NumberFormatException: For input string: ""

新版Swagger需要賦值,而且類型需要和dataType相符

image.png

參考資料:

1)Spring Boot中使用Swagger2構(gòu)建強大的RESTful API文檔 (推薦,主要是參考這篇寫的)
2)[Spring Boot - Enabling Swagger2] (https://www.tutorialspoint.com/spring_boot/spring_boot_enabling_swagger2.htm)
3) [SpringFox的更新記錄] (http://springfox.github.io/springfox/docs/current/#changes-in-swagger-ui
4)[SpringFox 3.0 升級指南] https://blog.csdn.net/qq_15973399/article/details/107436089

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容