天天看點

Springboot 配置Swagger (親測)

一、Swagger 是什麼

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

總體目标是使用戶端和檔案系統作為伺服器以同樣的速度來更新。檔案的方法、參數和模型緊密內建到伺服器端的代碼,允許 API 來始終保持同步。Swagger 讓部署管理和使用功能強大的 API 從未如此簡單。

簡單來說,就是接口發生修改,運作後,swagger能立即跟着修改,能直接測試,檢視接口文檔。

今天先實作哈,後續再詳細深入講解都有哪些用法

二、Swagger 如何配置

2.1 添加pom依賴

<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.2 增加配置類

@Configuration
@EnableSwagger2
public class Swagger {

    @Bean
    public Docket createRestApi() {
        ParameterBuilder tokenPar = new ParameterBuilder();
        List<Parameter> pars = new ArrayList<Parameter>();
        tokenPar.name("Authorization").description("AccessToken令牌").modelRef(new ModelRef("string")).parameterType("header").required(false).build();
        pars.add(tokenPar.build());
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.demo.controller"))
                .apis(RequestHandlerSelectors.withClassAnnotation(Api.class))
                .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
                .paths(PathSelectors.any())
                .build()
                .globalOperationParameters(pars);
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("JAVA接口文檔")
                .description("接口描述")
                .termsOfServiceUrl("http://www.baidu.com/")
                .version("1.0")
                .build();
    }      

3、如何引用

首先在接口類上加:

Api(tags={"字典接口服務"})

在方法上加:

@ApiOperation(value = "字典查詢接口")

如下圖:

Springboot 配置Swagger (親測)

運作Springboot 項目,通路位址:​​http://localhost:8087/swagger-ui.html​​

如下圖就表示swagger配置成功了