【java框架】SpringBoot(3) -- SpringBoot集成Swagger2


1.SpringBoot web項目集成Swagger2

1.1.認識Swagger2

Swagger 是一個規范和完整的框架,用於生成、描述、調用和可視化 RESTful 風格的 Web 服務。總體目標是使客戶端和接口文檔系統作為服務器以同樣的速度來更新。文檔的接口方法,參數和模型緊密集成到服務器端的代碼,使用API來保持前后端接口的更新同步。解決了前后端分離開發中的痛點。
 
Swagger2官方文檔:https://swagger.io
 

1.2.集成Swagger2初體驗

①基於SpringBoot Initializr來創建一個web項目,並引入相關依賴:

<!--引入swagger2依賴及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>

依賴組件下載地址:https://mvnrepository.com/artifact/io.springfox

 

②創建Swagger2Config配置類,增加API應用配置信息:

//將此類交給Spring管理,表示一個配置類
@Configuration
//開啟Swagger2
@EnableSwagger2
public class Swagger2Config {
    /**
     * 創建API應用
     * apiInfo() 增加API相關信息
     * 通過select()函數返回一個ApiSelectorBuilder實例,用來控制哪些接口暴露給Swagger來展現,
     * 本例采用指定掃描的包路徑來定義指定要建立API的目錄
     *
     * @return 返回Swagger的Docket配置Bean實例
     */
    @Bean
    public Docket createRestApi(Environment environment) {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .enable(true)  //enable是否啟動swagger,如果為False,則swagger不能在瀏覽器中訪問
                .select()
                //指定API對象掃描哪個包下面的controller
                //參數any():掃描全部; none():都不掃描
                //withClassAnnotation:掃描類上的注解,參數是一個注解的反射對象
                //withMethodAnnotation:掃描方法上的注解
                .apis(RequestHandlerSelectors.basePackage("com.fengye.swagger2.controller"))
                //過濾什么路徑
                .paths(PathSelectors.any())
                .build();
    }

    /**
     * 創建該API的基本信息(這些基本信息會展現在文檔頁面中)
     * 訪問地址:http://項目實際地址/swagger-ui.html
     * @return  返回API基本信息
     */
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                //Swagger2展示界面的標題(重要)
                .title("Spring Boot使用Swagger2構建的Restful API")
                //描述信息(主要)
                .description("Swagger2 makes develop more easily")
                .version("1.0")
                .termsOfServiceUrl("https://swagger.io/docs")
                .license("Apache 2.0")
                .licenseUrl("http://www.apache.org/licenses/LICENSE-2.0")
                //作者信息
                .contact(new Contact("fengye", "https://www.cnblogs.com/yif0118/",
                        "hyfmailsave@163.com")).build();
    }
}

 

③創建Controller接口類測試接口:

@RestController
@RequestMapping("/oss")
@Api(value = "接口演示",description = "用來演示Swagger的一些注解")
public class TestController {
    @ApiOperation(value="修改用戶密碼", notes="根據用戶id修改密碼")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType="query", name = "userId", value = "用戶ID", required = true, dataType = "Integer"),
            @ApiImplicitParam(paramType="query", name = "password", value = "舊密碼", required = true, dataType = "String"),
            @ApiImplicitParam(paramType="query", name = "newPassword", value = "新密碼", required = true, dataType = "String")
    })
    @RequestMapping("/updatePassword")
    public String updatePassword(@RequestParam(value="userId") Integer userId, @RequestParam(value="password") String password,
                                 @RequestParam(value="newPassword") String newPassword){
        if(userId <= 0 || userId > 2){
            return "未知的用戶";
        }
        if(StringUtils.isEmpty(password) || StringUtils.isEmpty(newPassword)){
            return "密碼不能為空";
        }
        if(password.equals(newPassword)){
            return "新舊密碼不能相同";
        }
        return "密碼修改成功!";
    }
}

 

④啟動項目,訪問接口url地址信息:

http://項目實際地址/swagger-ui.html

 

2.Swagger高級配置應用

2.1.多場景啟用配置

在實際開發場景中,有時我們需要在開發時使用Swagger接口文檔,但是在實際上線或生產環境中並不想使用,那么就需要讀取實際環境信息進行啟動Swagger。

具體配置如下:

//將此類交給Spring管理,表示一個配置類
@Configuration
//開啟Swagger2
@EnableSwagger2
public class Swagger2Config {
    /**
     * 創建API應用
     * apiInfo() 增加API相關信息
     * 通過select()函數返回一個ApiSelectorBuilder實例,用來控制哪些接口暴露給Swagger來展現,
     * 本例采用指定掃描的包路徑來定義指定要建立API的目錄
     *
     * @return 返回Swagger的Docket配置Bean實例
     */
    @Bean
    public Docket createRestApi(Environment environment) {
        //設置要顯示的Swagger環境
        Profiles profiles = Profiles.of("dev", "test");
        //獲取當前項目中的環境,看是否一致
        boolean flag = environment.acceptsProfiles(profiles);
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .enable(flag)  //enable是否啟動swagger,如果為False,則swagger不能在瀏覽器中訪問
                .select()
                //指定API對象掃描哪個包下面的controller
                //參數any():掃描全部; none():都不掃描
                //withClassAnnotation:掃描類上的注解,參數是一個注解的反射對象
                //withMethodAnnotation:掃描方法上的注解
                .apis(RequestHandlerSelectors.basePackage("com.fengye.swagger2.controller"))
                //過濾什么路徑
                .paths(PathSelectors.any())
                .build();
    }
}

 

同時設置相關的環境配置信息:

 

application.properties:

#確認啟用開發環境--swagger啟用
spring.profiles.active=dev

application-dev.properties與application-pro.properties:

server.port=8081  #開發環境
server.port=8082  #生產環境

 

2.2.接口文檔分組顯示

在實際項目開發過程中,一個項目開發者有成百上千個接口文檔,如果不進行分組,那么集合在一個Swagger頁面中的接口就會很多,不便於查詢和展示,

那么對不同的開發者來進行分組顯示,不同的開發者命名自己的開發接口,就非常有必要了。

而Swagger配置中提供了groupName()進行分組顯示:

@Bean
    public Docket devDocket1(){
        //由開發者自己管理對應的類,編寫controller對應的包
        return new Docket(DocumentationType.SWAGGER_2).groupName("A");
    }

    @Bean
    public Docket devDocket2(){
        return new Docket(DocumentationType.SWAGGER_2).groupName("B");
    }

    @Bean
    public Docket devDocket3(){
        return new Docket(DocumentationType.SWAGGER_2).groupName("C");
    }    

 

分組效果:

 

2.3.Swagger Api接口注釋

常用到的注解有:

  • Api
  • ApiModel
  • ApiModelProperty
  • ApiOperation
  • ApiParam
  • ApiResponse
  • ApiResponses
  • ResponseHeader

①Api

Api 用在類上,說明該類的作用。可以標記一個Controller類做為swagger 文檔資源,使用方式:

@Api(value = "/user", description = "Operations about user")

 

②ApiOeration

ApiOperation:用在方法上,說明方法的作用,每一個url資源的定義,使用方式:

@ApiOperation(
          value = "Find purchase order by ID",
          notes = "For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions",
          response = Order,
          tags = {"Pet Store"})

 

③ApiParam

ApiParam請求屬性,使用方式:

public ResponseEntity<User> createUser(@RequestBody @ApiParam(value = "Created user object", required = true)  User user)

與Controller中的方法並列使用。

 

④ApiResponse

ApiResponse:響應配置,使用方式:

@ApiResponse(code = 400, message = "Invalid user supplied")

 

⑤ApiResponses

ApiResponses:響應集配置,使用方式:

 @ApiResponses({ @ApiResponse(code = 400, message = "Invalid Order") })

 

⑥ResponseHeader

響應頭設置,使用方法:

@ResponseHeader(name="head1",description="response head conf")

 

⑦其它

  • @ApiImplicitParams:用在方法上包含一組參數說明;
  • @ApiImplicitParam:用在@ApiImplicitParams注解中,指定一個請求參數的各個方面
  1. paramType:參數放在哪個地方
  2. name:參數代表的含義
  3. value:參數名稱
  4. dataType: 參數類型,有String/int,無用
  5. required : 是否必要
  6. defaultValue:參數的默認值
  • @ApiResponses:用於表示一組響應;
  • @ApiResponse:用在@ApiResponses中,一般用於表達一個錯誤的響應信息;
  1. code: 響應碼(int型),可自定義
  2. message:狀態碼對應的響應信息
  • @ApiModel:描述一個Model的信息(這種一般用在post創建的時候,使用@RequestBody這樣的場景,請求參數無法使用@ApiImplicitParam注解進行描述的時候;
  • @ApiModelProperty:描述一個model的屬性。
更詳細Swagger接口Api注解說明請參閱簡書:https://www.jianshu.com/p/12f4394462d5
 
最新Swagger2  3.0版本配置詳情請見:
 

本博客寫作參考文檔相關:

https://www.jianshu.com/p/66a14ea07622  《簡書--Swagger使用手冊》

https://www.jianshu.com/p/12f4394462d5    《簡書--Swagger常用注解說明》

https://swagger.io/irc/

 

示例代碼已上傳至Github地址:

https://github.com/devyf/SpringBoot_Study/tree/master/springboot_swagger2


免責聲明!

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



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