首頁  >  文章  >  Java  >  SpringBoot整合Swagger的方法是什麼

SpringBoot整合Swagger的方法是什麼

WBOY
WBOY轉載
2023-05-31 10:20:22741瀏覽

    Spring Boot 是一個基於 Spring 框架的輕量級開源框架,它的出現極大地簡化了 Spring 應用的建構和開發。在開發過程中,介面文件是非常重要的一環,它不僅方便開發者查看和理解介面的功能和參數,還能幫助前後端開發協同工作,提高開發效率。

    一、關於 Swagger

    Swagger 是一個 RESTful 介面文件的規格和工具集,它的目標是統一 RESTful 介面文件的格式和規格。在開發過程中,介面文件是非常重要的一環,它不僅方便開發者查看和理解介面的功能和參數,還能幫助前後端開發協同工作,提高開發效率。 Spring Boot 可以整合 Swagger 來自動產生介面文件。透過使用註解描述接口,Swagger能夠自動產生接口文件。

    二、Swagger 的安裝

    1、下載Swagger

    Swagger 的官方網站是https://swagger.io/,我們可以在這裡下載最新版本的Swagger 。

    2、安裝 Swagger

    解壓縮下載的 Swagger 到指定目錄即可,這個安裝過程相當簡單。在解壓縮後的目錄中,我們可以找到 swagger-ui.html 頁面,這個頁面就是 Swagger 的 UI 介面。

    三、Swagger 的使用

    1、寫介面

    在寫介面時,我們需要使用 Swagger 的註解來描述介面資訊。常用的註解包括:

    • @Api:用來描述介面的類別或介面

    • ##@ApiOperation:用來描述介面的方法

    • @ApiParam:用於描述介面的參數

    • @ApiModel:用於描述資料模型

    • @ApiModelProperty:用來描述資料模型的屬性

    例如,我們寫一個簡單的介面:

    @RestController
    @Api(tags = "用户接口")
    public class UserController {
     
        @GetMapping("/user/{id}")
        @ApiOperation(value = "根据 ID 获取用户信息")
        public User getUserById(@ApiParam(value = "用户 ID", required = true) @PathVariable Long id) {
            // 根据 ID 查询用户信息
        }
    }

    在上面的程式碼中,@Api表示該類別是使用者接口,@ApiOperation 表示方法是取得使用者資訊的接口,@ApiParam 表示該參數是使用者ID,@PathVariable 表示該參數是路徑參數。

    2、啟用 Swagger

    在 Spring Boot 中,我們可以透過新增 Swagger 相關的依賴來啟用 Swagger。

    我們可以在 pom.xml 檔案中加入以下依賴:

    <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>

    在 Spring Boot 中,我們還需要新增設定類別來設定 Swagger。配置類別的程式碼如下:

    @Configuration
    @EnableSwagger2
    public class SwaggerConfig {
     
        @Bean
        public Docket api() {
            return new Docket(DocumentationType.SWAGGER_2)
                    .select()
                    .apis(RequestHandlerSelectors.basePackage("com.example.demo.controller"))
                    .paths(PathSelectors.any())
                    .build()
                    .apiInfo(apiInfo());
        }
     
        private ApiInfo apiInfo() {
            return new ApiInfoBuilder()
                    .title("接口文档")
                    .description("接口文档")
                    .version("1.0.0")
                    .build();
        }
    }

    在上面的程式碼中,@Configuration 表示該類別是一個配置類,@EnableSwagger2 表示啟用 Swagger。在 api() 方法中,我們透過 `select() 方法配置掃描的套件路徑,paths() 方法配置介面的存取路徑,apiInfo() 方法配置介面文件的相關資訊。

    3、檢視介面文件

    啟動 Spring Boot 應用程式後,我們可以在瀏覽器中造訪 http://localhost:8080/swagger-ui.html 來檢視介面文件。在 Swagger UI 頁面中,我們可以看到所有的介面訊息,包括介面名稱、請求方式、請求路徑、請求參數、回應參數等。

    四、Swagger 的進階使用

    1、描述資料模型

    #我們可以用 

    @ApiModel 和 @ApiModelProperty 註解來描述資料模型和屬性。例如,我們可以寫一個User 類,並在類別上使用@ApiModel 和

    @ApiModelProperty 注解来描述该数据模型:
    
    @ApiModel(description = "用户信息")
    public class User {
     
        @ApiModelProperty(value = "用户 ID", example ="1") 
        private Long id;
    
    	@ApiModelProperty(value = "用户名", example = "张三")
    	private String username;
    
    	@ApiModelProperty(value = "密码", example = "123456")
    	private String password;
    
    	// 省略 getter 和 setter 方法
    }

    在上面的程式碼中,@ApiModel 表示該類別是一個資料模型,@ApiModelProperty 表示該屬性是資料模型的一個屬性,value 屬性表示屬性的描述,example 屬性表示屬性的範例值。

    2、描述枚舉類型

    我們可以使用 

    @ApiModel 和 @ApiModelProperty 註解來描述枚舉類型。例如,我們可以編寫一個Gender 枚舉類型,並在枚舉值上使用@ApiModelProperty 註解來描述該枚舉值:

    @ApiModel(description = "性别") public enum Gender {
    
    @ApiModelProperty(value = "男")
    MALE,
    
    @ApiModelProperty(value = "女")
    FEMALE;
    }

    在上面的程式碼中,@ApiModel 表示該枚舉類型是一個描述性別的列舉類型,@ApiModelProperty 表示該枚舉值是描述男性的枚舉值或描述女性的枚舉值。

    3、描述回應參數

    我們能夠利用 @ApiResponses 和 @ApiResponse 註解來定義 API 的回應參數。例如,我們可以寫一個getUserById() 方法,並在方法上使用@ApiResponses 和@ApiResponse 註解來描述該方法的回應參數:

    @GetMapping("/user/{id}")
    @ApiOperation(value = "根据 ID 获取用户信息") 
    @ApiResponses({ @ApiResponse(code = 200, message = "请求成功", response = User.class), 
    @ApiResponse(code = 404, message = "用户不存在") }) 
    public User getUserById(@ApiParam(value = "用户 ID", required = true) @PathVariable Long id) 
    { 
    	// 根据 ID 查询用户信息 
    }

    在上面的程式碼中,@ApiResponses 表示該方法的回應參數,@ApiResponse 表示此回應參數的描述,code 屬性表示回應碼,message 屬性表示回應訊息,response 屬性表示回應的資料模型。

    五、Swagger 的進階使用

    1、配置全域參數

    透過使用方法 globalOperationParameters(),我們能夠在組態類別中配置全域參數。我們可以透過配置一個全域的 Authorization 參數來進行授權

    @Configuration
    @EnableSwagger2
    public class SwaggerConfig {
     
        @Bean
        public Docket api() {
            return new Docket(DocumentationType.SWAGGER_2)
                    .select()
                    .apis(RequestHandlerSelectors.basePackage("com.example.demo.controller"))
                    .paths(PathSelectors.any())
                    .build()
                    .globalOperationParameters(Arrays.asList(
                            new ParameterBuilder()
                                    .name("Authorization")
                                    .description("授权")
                                    .modelRef(new ModelRef("string"))
                                    .parameterType("header")
                                    .required(false)
                                    .build()
                    ))
                    .apiInfo(apiInfo());
        }
     
        private ApiInfo apiInfo() {
            return new ApiInfoBuilder()
                    .title("接口文档")
                    .description("接口文档")
                    .version("1.0.0")
                    .build();
        }
     
    }

    在上面的程式碼中,我們透過 globalOperationParameters() 方法來配置一個全域的 Authorization 參數,用於授權。

    2、配置安全协议

    通过在配置类中调用 securitySchemes() 方法,我们能够进行安全协议的配置。举个例子,可以设置 Bearer Token 作为安全协议

    @Configuration
    @EnableSwagger2
    public class SwaggerConfig {
     
        @Bean
        public Docket api() {
            return new Docket(DocumentationType.SWAGGER_2)
                    .select()
                    .apis(RequestHandlerSelectors.basePackage("com.example.demo.controller"))
                    .paths(PathSelectors.any())
                    .build()
                    .securitySchemes(Arrays.asList(
                            new ApiKey("Bearer", "Authorization", "header")
                    ))
                    .apiInfo(apiInfo());
        }
     
        private ApiInfo apiInfo() {
            return new ApiInfoBuilder()
                    .title("接口文档")
                    .description("接口文档")
                    .version("1.0.0")
                    .build();
        }
     
    }

    在上面的代码中,我们通过 securitySchemes() 方法来配置一个 Bearer Token 安全协议。

    3、配置安全上下文

    使用 securityContexts() 方法配置安全上下文是配置类中的一种可选方法。举个例子,我们可以设置一个安全上下文来在Swagger UI中展示认证按钮:

    @Configuration
    @EnableSwagger2
    public class SwaggerConfig {
     
        @Bean
        public Docket api() {
            return new Docket(DocumentationType.SWAGGER_2)
                    .select()
                    .apis(RequestHandlerSelectors.basePackage("com.example.demo.controller"))
                    .paths(PathSelectors.any())
                    .build()
                    .securitySchemes(Arrays.asList(
                            new ApiKey("Bearer", "Authorization", "header")
                    ))
                    .securityContexts(Collections.singletonList(
                            SecurityContext.builder()
                                    .securityReferences(Collections.singletonList(
                                            new SecurityReference("Bearer", new AuthorizationScope[0])
                                    ))
                                    .build()
                    ))
                    .apiInfo(apiInfo());
        }
     
        private ApiInfo apiInfo() {
            return new ApiInfoBuilder()
                    .title("接口文档")
                    .description("接口文档")
                    .version("1.0.0")
                    .build();
        }
     
    }

    在上面的代码中,我们通过 securityContexts() 方法来配置一个安全上下文,用于在 Swagger UI 中显示认证按钮。

    4、配置忽略参数

    在API文档中,可能有些参数包含敏感信息,因此需要保护这些信息不被公示。我们可以使用 @ApiIgnore 注解来忽略这些参数。在 User 类中,我们可以使用 @ApiIgnore 注解来排除密码参数

    @ApiModel(description = "用户信息")
    public class User {
     
        @ApiModelProperty(value = "用户 ID", example = "1")
        private Long id;
     
        @ApiModelProperty(value = "用户名", example = "张三")
        private String username;
     
        @ApiModelProperty(hidden = true)
        @ApiIgnore
        private String password;
     
        // 省略 getter 和 setter 方法
    }

    在上面的代码中,@ApiModelProperty(hidden = true) 表示该参数是隐藏的,@ApiIgnore 表示忽略该参数。

    以上是SpringBoot整合Swagger的方法是什麼的詳細內容。更多資訊請關注PHP中文網其他相關文章!

    陳述:
    本文轉載於:yisu.com。如有侵權,請聯絡admin@php.cn刪除