IDEA中SpringBoot集成Swagger总结,思路清晰!

总结一下Swagger

Swagger是什么?

现在比较流行的是前后端分离的开发方式,后端写好接口后撰写接口文档,前端根据接口文档调用接口进行开发。

Swagger主要是自动生成接口文档的一个工具,并且附带测试接口(类似Postman)功能。

为什么要用Swagger?

接口文档谁写谁知道,繁琐,容易出错,且每个人的写法,风格等不好去规范。

用起Swagger解放双手,减少错误,规范文档,实时方便可调试,对于前端后端都是一件好事。

Swagger怎么用?

以目前流行的SpringBoot框架为例,介绍如何快速集成Swagger帮助我们开发。

1、导入依赖

<!--Swagger2依赖-->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.7.0</version>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.7.0</version>
        </dependency>

ps:如你在使用2.9.2或以上版本出现兼容问题,请移步此博客。

解决SpringBoot集成Swagger2.9.2版本兼容问题

2、编写Swagger配置类

@Configuration 声明为配置类

@EnableSwagger2 启用Swagger注解

/**
 * Swagger的配置类
 */
@Configuration
@EnableSwagger2
public class SwaggerConfig {
    //测试API
    @Bean
    public Docket myDocket(){
        return new Docket(DocumentationType.SWAGGER_2)
                .groupName("测试")
                .apiInfo(myApiInfo())//调用的api描述方法
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.coderman.api.test"))//扫描的API包路径
                .build();
    }

    public ApiInfo myApiInfo(){
        return new ApiInfoBuilder()
                .title("测试API文档")
                .version("1.0")
                .build();
    }

ps:groupName表示分组,如果要建立多个组别,写多组docket和apiInfo方法就好了。 

3、编写实体类

@ApiModel用于实体类上,value表示对象名,description表示对象描述

@ApiModel(value = "对象名", description ="对象描述")
public class Test {

    private Integer i;

}

4、编写Controller类

@Api 表示这个类是swagger的资源,value和tags都是接口说明

@ApiOperation 用于方法上,value表示接口描述,notes表示提示内容

@ApiParam用于参数上,name表示参数名,notes表示参数说明,required表示表示是否必填,值为true或false

@RestController
@Api(value = "接口说明" , tags = "接口说明")
public class TestController {

    @ApiOperation(value = "方法描述" , notes = "提示内容")
    @PostMapping (value = "/testPost")
    public void testPost(@RequestBody Test t){

    }

    @ApiOperation(value = "方法描述" , notes = "提示内容")
    @GetMapping(value = "/testGet")
    public void testGet(@PathVariable @ApiParam(name = "参数名",value = "参数说明",required = true) Integer i){

    }

}

5、访问测试

项目启动后,访问:http://localhost:8080/swagger-ui.html

ps:这个是默认地址,ip和端口号根据情况自行修改

访问成功后效果如下图

如果想要了解更多可以前往Swagger的官网

地址:https://swagger.io/

猜你喜欢

转载自blog.csdn.net/weixin_42559574/article/details/108445846