10分鐘學會Swagger

10分鐘學會Swagger

0.前置知識

oas:OpenAPI Specification 即(OpenAPI 規範)java

官方文檔:https://swagger.io/spring

1.導入依賴

<!-- https://mvnrepository.com/artifact/io.springfox/springfox-boot-starter -->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-boot-starter</artifactId>
            <version>3.0.0</version>
        </dependency>

2.在啓動類上添加註解

@EnableOpenApiapi

@SpringBootApplication
@EnableOpenApi
public class SwaggerApplication {

    public static void main(String[] args) {
        SpringApplication.run(SwaggerApplication.class, args);
    }

}

3.關於Docket

它是一個swagger的一個插件類app

自定義swaggeride

// 構造方法,須要傳入一個documentationType類
public Docket(DocumentationType documentationType) {
        this.apiInfo = ApiInfo.DEFAULT;
        this.groupName = "default";
        this.enabled = true;
        this.genericsNamingStrategy = new DefaultGenericTypeNamingStrategy();
        this.applyDefaultResponseMessages = true;
        this.host = "";
        this.pathMapping = Optional.empty();
        this.apiSelector = ApiSelector.DEFAULT;
        this.enableUrlTemplating = false;
        this.vendorExtensions = new ArrayList();
        this.globalRequestParameters = new ArrayList();
        this.documentationType = documentationType;
    }

在這裏插入圖片描述

咱們能夠調用apiInfo() 方法自定信息。學習

contact 就是簡單的一個簡單的類(表示做者聯繫方式的) ,默認爲空。測試

三個屬性:name,url,emaiui

title 頁面的標題(string 類型)this

這一個板塊是apiInfourl

在這裏插入圖片描述

ApiInfo 能夠經過ApiInfoBuilder 這個類的build()方法來構造

@Bean
    public Docket docket(){
        return new Docket(DocumentationType.OAS_30).apiInfo(
                new ApiInfoBuilder().contact(new Contact("Herio","www.he-hao.top","1479898695@qq.com"))
                .title("Herio的OpenApi")
                .version("v1.0")
                .description("這是一段介紹")
                .build()
        );
    }

在這裏插入圖片描述

值得注意的是默認的contact的url 你在頁面上點擊後跳轉會自動加上前綴:

http://localhost:8080/swagger-ui/ ,這個應該能夠手動修改。

4.接口添加註釋

@Api(tags="Hello控制器")
public class HelloController {

    @ApiOperation(value="測試請求",notes="備註的方法")
    @GetMapping("/hello")
    public String hello(){
        return "hello";
    }
}

在這裏插入圖片描述

5.只掃描某一類或某一個包下的接口

@Bean
//只掃描以/hello 開頭的接口
    public Docket docket1(){
        return new Docket(DocumentationType.OAS_30)
        .groupName("group2").select().paths(PathSelectors.ant("/hello/**")).build();
    }

//只掃描com.example.swagger.controller 包下的接口
@Bean
    public Docket docket2(){
        return new Docket(DocumentationType.OAS_30).groupName("group3")
        .select().apis(RequestHandlerSelectors.basePackage("com.example.swagger.controller")).build();
    }

6. 使用第三方UI

在這裏插入圖片描述


7.學習文章

傳送門

相關文章
相關標籤/搜索