Swagger配置和使用


1、在pom.xml中引入依賴

<!--引入swagger2的jar包-->
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>2.9.2</version>
</dependency>
<!--引入接口文檔頁面UI-->
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>2.9.2</version>
</dependency>

2、新建config文件夾,編寫配置文件SwaggerConfig.java

package com.gxa.config;

import io.swagger.annotations.Api;
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;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@Configuration    //依賴Spring注解
@EnableSwagger2
public class SwaggerConfig {
    @Bean    //依賴Spring注解
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)   //使用2.0版本
                .enable(true)          // 是否禁用swagger,可以控制全局
                .useDefaultResponseMessages(false)   //是否使用默認響應消息的方式
                .apiInfo(apiInfo())        //創建api的基本信息,如:標題、描述、版本等
                .select()
                .apis(RequestHandlerSelectors.withClassAnnotation(Api.class))
                .paths(PathSelectors.any())
                .build();
    }
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("swagger API文檔")
                .description("測試接口文檔")
                .version("1.0")
                .build();
    }
}

3、在SpringMVC配置文件中配置掃描

    <!--  掃描com.gxa.config  -->
    <context:component-scan base-package="com.gxa.config"/>

4、swagger使用

4.1、@Api 修飾整個類,描述Controller的作用

@Controller
@Api(value = "用戶數據test",tags = "用戶數據接口API")  //value:代表代碼級描述   tags:代表頁面級描述
public class Swagger2Controller {
     // code..
}

在http://localhost:8080/swagger-ui.html地址中查看下面的效果

4.2、@ApiOperation 修飾一個方法,代表此方法為一個接口,通常配合Spring MVC RequestMapping注解一起放置在方法上

@RequestMapping(value = "/think_login",method = RequestMethod.GET)
@ApiOperation(value = "用戶登錄接口",notes = "驗證用戶的用戶名和密碼",httpMethod = "post", response = String.class)  //value:代表頁面級接口描述 notes:代表完整接口說明 httpMethod:可選參數,代表調用的請求方式,但是swagger標示的spring mvc的請求方式,所以即使像上面那樣,定義為了post,但是Spring MVC是get請求,在接口文檔中還是呈現get方式。 response:可選參數,代表返回類型
public String login() {
    return "login";
}

4.3、@ApiImplicitParam 代表一個請求參數的定義,通常與Spring MVC的RequestParam注解一起使用。

@RequestMapping(value = "/think_login",method = RequestMethod.GET)
@ApiOperation(value = "用戶登錄接口",notes = "驗證用戶的用戶名和密碼",httpMethod = "post", response = String.class)
@ApiImplicitParam(name = "username",value = "用戶名",required = true,dataType = "String",paramType = "query") 
/**
 * name:代表頁面級描述參數名
 * value:代表頁面級描述參數說明
 * required:代表頁面級展示是否一定要輸入
 * dataType:代表頁面級描述參數類型
 * paramType:
 *      path 以地址的形式提交數據
 *      query 直接跟參數完成自動映射賦值
 *      body 以流的形式提交 僅支持POST
 *      header 參數在request headers 里邊提交
 *      form 以form表單的形式提交 僅支持POST
 * 被這個paramType坑過,當發POST請求的時候,當時接受的整個參數,不論用body還是query,后台都會報Body Missing錯誤;這個參數和SpringMvc中的@RequestBody沖突,去掉paramType對接口測試並沒有影響。
 */
public String login(@RequestParam(name = "username") String username) {
    return username;
}

4.4、@ApiImplicitParams 代表多個形式參數的表達形式,內部是數組形態,可以包含多個@ApiImplicitParam注解標記

@RequestMapping(value = "/think_login",method = RequestMethod.GET)
@ApiOperation(value = "用戶登錄接口",notes = "驗證用戶的用戶名和密碼",httpMethod = "post", response = String.class)
@ApiImplicitParams({
        @ApiImplicitParam(name = "username",value = "用戶名",paramType = "query",dataType = "String",required = true),
        @ApiImplicitParam(name = "password",value = "密碼",paramType = "query",dataType = "String",required = true)
})
public String login(@RequestParam(name = "username") String username,
                    @RequestParam(name = "password") String password) {
    return username + password;
}

4.5、@ApiParam Json參數的定義,通常與Spring MVC的@RequestBody配合使用,特別注意的是,因為是json參數請求,所以接收方式必須是post,如果使用的get可能會出現錯誤

@RequestMapping(value = "/think_login",method = RequestMethod.POST)
@ResponseBody
@ApiOperation(value = "用戶登錄接口",notes = "驗證用戶的用戶名和密碼",httpMethod = "post", response = String.class)
public User login(@RequestBody @ApiParam(name = "user",value = "用戶名和密碼",required = true) User user) {  //name:頁面級描述形式參數的名字 value:頁面級形參的說明 required:頁面級標注是否一定需要輸入
    return user;
}

4.6、@ApiModel和@ApiProperty @ApiModel和@ApiModelProperty兩個注解的作用是在接口文檔中顯示出entity的完整信息,@ApiModel定義在entity類名上,@ApiModelProperty定義在entity的屬性上

@ApiModel(value = "用戶基礎資料的實體")
public class ThinkUser {
    @ApiModelProperty(name = "id",notes = "主鍵",dataType = "String",required = false) //name:頁面級字段名展示 notes:頁面級字段名描述 dataType:頁面級字段類型說明 required:頁面級標注字段是否必輸
    private String id;

    @ApiModelProperty(name = "username",notes = "用戶名",dataType = "String",required = true)
    private String username;

    @ApiModelProperty(name = "password",notes = "密碼",dataType = "String",required = true)
    private String password;
// set、get方法...
}

4.7、@ApiResponses和@ApiResponse @ApiResponses包含多個響應結果模板,在此注解中加入@ApiResponse代表每一種響應格式

@RequestMapping(value = "/think_login",method = RequestMethod.POST)
@ResponseBody
@ApiOperation(value = "用戶登錄接口",notes = "驗證用戶的用戶名和密碼",httpMethod = "post", response = String.class)
@ApiResponses({
        @ApiResponse(code=200,message="請求成功"),     //code:代表狀態碼 message:代表說明信息
        @ApiResponse(code=404,message="找不到頁面"),
        @ApiResponse(code=500,message="后台服務錯誤")
})
public ThinkUser login(@RequestBody @ApiParam(name = "thinkUser",value = "用戶名和密碼",required = true) ThinkUser thinkUser) {
    return thinkUser;
}

4.8、@ApiIgnore 定義在類上,代表此類會swagger忽略,定義在方法上,代表此方法被swagger忽略

5、禁用Swagger 禁用處理最直接的方式,就是剝離掉所有的swagger注解

第一步,修改enable屬性為false,這樣處理以后再次訪問swagger-ui.html頁面會發現,頁面中的信息不會暴露了,但是還會有對應的響應存在,這樣會讓外部人員知道此系統使用了swagger技術,如下效果:

@Bean
public Docket createRestApi() {
    return new Docket(DocumentationType.SWAGGER_2)
            .enable(false)          // 是否禁用swagger
            .useDefaultResponseMessages(false)
            .apiInfo(apiInfo())
            .select()
            .apis(RequestHandlerSelectors.withClassAnnotation(Api.class))
            .paths(PathSelectors.any())
            .build();
}

第二步,增加一個controller,管理/swagger-ui路徑,如下:

@RequestMapping("/swagger-ui")
public String getUserInfo() {
    return "error";
}

這樣的方式,是利用了spring mvc優先查找requestMapping的功能,這樣相當於攔截了這個頁面路徑的請求,這時候訪問swagger-ui.html當出現錯誤提示,可以根據業務需要修改為任意的跳轉地址。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM