温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

SpringBoot整合Swagger的方法是什么

发布时间:2023-05-08 15:20:39 来源:亿速云 阅读:88 作者:iii 栏目:开发技术

本文小编为大家详细介绍“SpringBoot整合Swagger的方法是什么”,内容详细,步骤清晰,细节处理妥当,希望这篇“SpringBoot整合Swagger的方法是什么”文章能帮助大家解决疑惑,下面跟着小编的思路慢慢深入,一起来学习新知识吧。

    Spring Boot 是一个基于 Spring 框架的轻量级开源框架,它的出现极大地简化了 Spring 应用的搭建和开发。在开发过程中,接口文档是非常重要的一环,它不仅方便开发者查看和理解接口的功能和参数,还能帮助前后端开发协同工作,提高开发效率。

    一、关于 Swagger

    Swagger 是一个 RESTful 接口文档的规范和工具集,它的目标是统一 RESTful 接口文档的格式和规范。在开发过程中,接口文档是非常重要的一环,它不仅方便开发者查看和理解接口的功能和参数,还能帮助前后端开发协同工作,提高开发效率。在 Spring Boot 中,我们可以通过集成 Swagger 来实现接口文档的自动生成。Swagger 通过注解来描述接口,然后根据这些注解自动生成接口文档。

    二、Swagger 的安装

    1、下载 Swagger

    Swagger 的官方网站是 https://swagger.io/,我们可以在这里下载最新版本的 Swagger。

    2、安装 Swagger

    安装 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 注解来描述接口的响应参数。例如,我们可以编写一个 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、配置忽略参数

    在接口中,有些参数可能是敏感信息,我们不希望在接口文档中显示。我们可以使用 @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的方法是什么”文章已经介绍完毕,想要掌握这篇文章的知识点还需要大家自己动手实践使用过才能领会,如果想了解更多相关内容的文章,欢迎关注亿速云行业资讯频道。

    向AI问一下细节

    免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

    AI