Swagger UI是一個為項目提供可視API文檔的規(guī)范定義開源項目旬陡,它可以幫我們快速預(yù)覽項目接口,并提供模擬請求的功能语婴。下面以上一篇搭建好的SpringBoot項目為例描孟,介紹一下如何使用Swagger UI。
1.添加Swagger UI依賴
<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>
2.創(chuàng)建配置文件SwaggerConfig
首先砰左,在啟動文件(此處為DemoApplication)同級目錄下創(chuàng)建一個config
文件夾用以配置項目相關(guān)信息匿醒。在該文件夾下創(chuàng)建一個SwaggerConfig.java
文件用以配置Swagger UI的相關(guān)信息,同時將Swagger注冊為Bean缠导,以使其注解有效廉羔。其代碼如下:
// SwaggerConfig.java
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo()).select().apis(RequestHandlerSelectors.any())
.paths(PathSelectors.any()).build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("Swagger Title") // 配置項目的Swagger UI標題
.description("Swagger Description") // 配置描述信息
.version("1.0.0-SNAPSHOT") // 項目版本信息
.build();
}
}
3.給Controller添加注解
以IndexController
為例,給代碼添加注解如下:
@Api(value = "index測試類", description = "描述信息")
@RestController
@RequestMapping("/index")
public class IndexController {
@ApiOperation(value = "index", notes = "home測試方法") // tags
@RequestMapping(value = "/home", method = RequestMethod.GET)
public String index() {
return "Hello,World";
}
}
訪問默認路徑http://localhost:8080/swagger-ui.html僻造,其效果如下:
Swagger UI初始化
到此憋他,Swagger UI簡單配置完成,日常使用不成問題髓削,深入使用可查看官方文檔:https://swagger.io/docs/
源碼訪問:Github e11b347