- 簡介
Swagger UI允許任何人—無論是您的開發團隊還是您的最終消費者—可視化並與API的資源交互,而不需要任何適當的實現邏輯。它是由您的OpenAPI(以前稱爲Swagger)規範自動生成的,帶有可視化文檔,便於後端實現和客戶端使用。
這是Swagger官網上對Swagger UI的介紹,簡單講就是它提供了一個可視化的API文檔
- 引入依賴
SpringBoot集成的依賴
<dependency>
<groupId>com.spring4all</groupId>
<artifactId>swagger-spring-boot-starter</artifactId>
<version>1.9.0.RELEASE</version>
</dependency>
或
<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>
- 創建Swagger配置類
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
/**
* @author By 尚
* @date 2019/4/2 18:08
*/
@Configuration
public class Swagger2Config {
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
// 該處可不指定組別,Swagger默認指定了一個名爲default的組
.groupName("myGroup")
.apiInfo(apiInfo())
.select()
//這裏採用包掃描的方式來確定要顯示的接口
.apis(RequestHandlerSelectors.basePackage("cn.hgd11.swagger.success.controller"))
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("Docker Operation Rest Api Doc")
.description("Docker Operation Api文檔")
.version("1.0")
.build();
}
}
說明:本例中使用掃描包的形式加載Controller層,Swagger也提供了其它的形式,如掃描配置了某些特定註解了類或是配置某些註解的方法。在使用中掃描包的形式最爲常見,本例也採用這樣的方法。
- 創建Controller
import cn.hgd11.swagger.success.entity.TestEntity;
import cn.hgd11.swagger.success.entity.TestEntity2;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @author :尚村山夫
* @date :Created in 2019/9/14 22:54
* @modified By:
*/
@RestController
@RequestMapping("test2")
@Api(tags = "測試2") // 對該Controller進行說明的註解,如"用戶管理","部門管理",本例"測試2"
public class Test2Controller {
@GetMapping
@ApiOperation("測試方法1") // 用戶對該接口進行說明的註解
public TestEntity testEntity(){
return new TestEntity();
}
@PostMapping
@ApiOperation("測試方法2") // 用戶對該接口進行說明的註解
public TestEntity testEntity(TestEntity2 testEntity2){
return new TestEntity();
}
}
在瀏覽器中訪問localhost:8412/swagger-ui.html,即可得到Swagger文檔。IP和端口據實際情況而定,訪問的頁面一定是swagger-ui.html
對於Swagger中如何進行參數說明及如何添加頭信息,如添加Authorization認證,請參考https://blog.csdn.net/shangcunshanfu/article/details/100838687Swagger使用介紹二之爲Controller中參數添加字段說明