Spring-Boot中結合Swagger-UI實現在線接口文檔

1.Swagger是什麼?

Swagger 是一個規範且完整的框架,用於生成、描述、調用和可視化 RESTful 風格的 Web 服務。

Swagger 的目標是對 REST API 定義一個標準且和語言無關的接口,可以讓人和計算機擁有無須訪問源碼、文檔或網絡流量監測就可以發現和理解服務的能力。當通過 Swagger 進行正確定義,用戶可以理解遠程服務並使用最少實現邏輯與遠程服務進行交互。與爲底層編程所實現的接口類似,Swagger 消除了調用服務時可能會有的猜測。(ps:來源於網上)

簡單來說:Swagger就是一個接口可視化文檔,它是在線的,在我們進行前後端分離開發的時候,方便前端人員與後端人員開發;減少因爲接口約定不一致的原因而多做的工作量。

2.怎麼去使用Swagger?

其實Swagger的使用很簡單,只需要簡單的幾步就可以使用了。ps:這裏使用Swagger是結合Spring-Boot的使用。

2.1 導入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>

        <dependency>
            <groupId>io.swagger</groupId>
            <artifactId>swagger-annotations</artifactId>
            <version>1.5.19</version>
        </dependency>

2.2 添加一個Swagger的配置類


@Configuration
@EnableSwagger2
public class SwaggerConfig {

    @Bean
    public Docket createRestApi(){
        return  new Docket(DocumentationType.SWAGGER_2)
                .groupName("hello")
                //接口文檔的信息
                .apiInfo(api())
                .select()
                //要掃描的Controller包的位置
                .apis(RequestHandlerSelectors.basePackage("com.example.wangwang.controller"))
                .paths(PathSelectors.any())
                .build();

    }

    private ApiInfo api() {
        return  new ApiInfoBuilder()
                .title("Spring-Boot中結合Swagger的使用")
                .description("沒什麼可描述的")
                .termsOfServiceUrl("www.baidu.com")
                .version("1.0.0")
                .build();
    }

}

2.3 在Controller中填寫Api的信息

常用註解

  • @Api:用於修飾Controller類,生成Controller相關文檔信息
  • @ApiOperation:用於修飾Controller類中的方法,生成接口方法相關文檔信息
  • @ApiParam:用於修飾接口中的參數,生成接口參數相關文檔信息
  • @ApiModelProperty:用於修飾實體類的屬性,當實體類是請求參數或返回結果時,直接生成相關文檔信息
@RestController
@Api(tags = "TestController",description = "測試接口")
public class TestController {



    @RequestMapping(value = "getUserInfo",method = RequestMethod.GET)
    @ApiOperation("獲取某用戶的信息")
    public String  showAlluser(){
        //這裏就不寫業務代碼了
        return  "hello";
    }
    @ApiOperation("更新用戶信息")
    @RequestMapping(value = "updateUser",method = RequestMethod.POST)
    public void updateUser(TbUser user){
        //這裏就不寫業務代碼了
    }

}

運行項目

訪問接口文檔的地址:

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

在這裏插入圖片描述
在這裏插入圖片描述
ps:當某接口的參數是一個實體類 可以加上@ApiModelProperty這個註解來描述相關的信息。

例如:在這裏插入圖片描述
實體類:在這裏插入圖片描述
完~~~~

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章