SpringBoot集成Swagger2

189 篇文章 3 订阅
80 篇文章 1 订阅

SpringBoot集成Swagger2

前端经常抱怨后端给的接口文档与实际情况不一致。
后端又觉得编写及维护接口文档会耗费不少精力,经常来不及更新。
其实无论是前端调用后端,还是后端调用后端,都期望有一个好的接口文档。

1.什么是Swagger2?它能干什么?
发现了痛点就要去找解决方案。解决方案用的人多了,就成了标准的规范,这就是Swagger的由来。
通过这套规范,你只需要按照它的规范去定义接口及接口相关的信息。再通过Swagger衍生出来的一系列项目和工具,就可以做到生成各种格式的接口文档,生成多种语言的客户端和服务端的代码,以及在线接口调试页面等等。
这样,如果按照新的开发模式,在开发新版本或者迭代版本的时候,只需要更新Swagger描述文件,就可以自动生成接口文档和客户端服务端代码,做到调用端代码、服务端代码以及接口文档的一致性。
2.Swagger2的优点
Swagger2的出现解决了上述问题。它作为一个规范和完整的框架,可以用于生成、描述、调用和可视化RESTful风格的Web服务。
接口文档在线自动生成,文档随接口变动实时更新,节省维护成本。
支持在线接口测试,不依赖第三方工具。
上面介绍完了Swagger2,那接下来就开始使用它。这里使用SpringBoot2.X集成Swagger2。

3.引入Swagger2的依赖
使用Swagger2只需要引入下面两个依赖即可:

...
<!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger-ui -->
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>2.9.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger2 -->
<dependency>
   <groupId>io.springfox</groupId>
   <artifactId>springfox-swagger2</artifactId>
   <version>2.9.2</version>
</dependency>
省略了SpringBoot相关的依赖...
1
2
3
4
5
6
7
8
9
10
11
12
13
14
4.配置Swagger2
下面简单说明该配置的作用

通过@Configuration注解,让 Spring加载该配置类。再通@EnableSwagger2注解来启用Swagger2。
成员方法 createRestApi 函数创建 Docket 的Bean之后,apiInfo() 用来创建该 Api 的基本信息(这些基本信息会展现在文档页面中)。select()返回一个 ApiSelectorBuilder实例用来控制哪些接口暴露给Swagger来展现,Swagger会扫描该包下所有 Controller类定义的API,并产生文档内容(除了被@ApiIgnore指定的请求)。
@EnableSwagger2
@Configuration
public class Swagger2Config {

    //api接口包扫描路径
    public static final String SWAGGER_SCAN_BASE_PACKAGE = "cn.zwq.controller";

    //Swagger2接口文档版本
    public static final String VERSION = "1.0.0";

    @Bean
    public Docket createRestApi(){
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage(SWAGGER_SCAN_BASE_PACKAGE))
                .paths(PathSelectors.any()) //可以根据url路径设置哪些请求加入文档,忽略哪些请求
                .build();
    }

    public ApiInfo apiInfo(){
        return new ApiInfoBuilder()
                .title("Spring Boot 测试使用 Swagger2 构建RESTful API") //设置文档的标题
                .description("REST API")    //设置文档的描述
                .version(VERSION)   //设置文档的版本
                .termsOfServiceUrl("")  //设置文档的License信息
                .contact(new Contact("zwq","https://blog.csdn.net/weixin_44176169","Xxx@163.com"))
                .build();
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
5.Swagger2注解详解
@Api:请求类的说明
@Api:放在请求的类上,与@Controller并列,说明类的作用,如用户模块,订单类等。
    tags="说明该类的作用"
1
2
@Api(tags = "用户模块")
@RestController
@RequestMapping("/user")
public class UserController {}
1
2
3
4
@ApiOperation:方法的说明
@ApiOperation:"用在请求的方法上,说明方法的作用"
    value="说明方法的作用"
    notes="方法的备注说明"
1
2
3
@ApiOperation(value = "跳转到用户登录页面",notes = "当访问项目根路径的时候,跳转到用户登录页面")
    @RequestMapping(value = "/",method = RequestMethod.GET)
    public String login(){
        return "login";
    }
1
2
3
4
5
@ApiImplicitParams、@ApiImplicitParam:方法参数的说明
@ApiImplicitParams:用在请求的方法上,包含一组参数说明
    @ApiImplicitParam:对单个参数的说明      
        name:参数名
        value:参数的汉字说明、解释
        required:参数是否必须传
        paramType:参数放在哪个地方
            · header --> 请求参数的获取:@RequestHeader
            · query --> 请求参数的获取:@RequestParam
            · path(用于restful接口)--> 请求参数的获取:@PathVariable
            · body(请求体)-->  @RequestBody User user
            · form(普通表单提交)     
        dataType:参数类型,默认String,其它值dataType="参数类型"       
        defaultValue:参数的默认值
1
2
3
4
5
6
7
8
9
10
11
12
13
@ApiOperation(value="更新用户详细信息", notes="根据url的id来指定更新对象,并根据传过来的user信息来更新用户详细信息")
@ApiImplicitParams({
        @ApiImplicitParam(name = "id", value = "用户ID", required = true, dataType = "Long"),
        @ApiImplicitParam(name = "user", value = "用户详细实体user", required = true, dataType = "User")
})
@RequestMapping(value="/{id}", method=RequestMethod.PUT)
public void putUser(@PathVariable Long id, @RequestBody User user) {
    User u = new User();
    users.put(id, u);
}
1
2
3
4
5
6
7
8
9
10
@ApiOperation(value="获取用户详细信息", notes="根据url的id来获取用户详细信息")
@ApiImplicitParam(name = "id", value = "用户ID", required = true, dataType = "Long")
@RequestMapping(value="/{id}", method=RequestMethod.GET)
public User getUser(@PathVariable Long id) {
    return users.get(id);
}
1
2
3
4
5
6
@ApiResponses、@ApiResponse:方法返回值的说明
@ApiResponses:方法返回对象的说明
    @ApiResponse:每个参数的说明
        code:数字,例如404
        message:信息,例如"请求参数没填好"
        response:抛出异常的类
1
2
3
4
5
@ApiResponses({
        @ApiResponse(code = 404,message = "请求路径找不到"),
        @ApiResponse(code = 400,message = "请求参数不正确")
})
@ApiOperation(value="获取用户详细信息", notes="根据url的id来获取用户详细信息")
@ApiImplicitParam(name = "id", value = "用户ID", required = true, dataType = "Long")
@RequestMapping(value="/{id}", method=RequestMethod.GET)
public User getUser(@PathVariable Long id) {
    return users.get(id);
}
1
2
3
4
5
6
7
8
9
10
@ApiModel:用于JavaBean上面,表示一个JavaBean
@ApiModel:用于JavaBean的类上面,表示此JavaBean整体的信息
    (这种一般用在post创建的时候,使用@RequestBody这样的场景,请求参数无法使用@ApiImplicitParam注解进行描述的时候)
1
2
@ApiModelProperty:用在JavaBean的属性上面,说明属性的含义
@Data
@ApiModel(value ="用户实体类",description = "封装用户信息")
public class User {
    @ApiModelProperty(name = "id",value = "用户id")
    private Long id;
    @ApiModelProperty(name = "username",value = "用户名")
    private String username;
    @ApiModelProperty(name = "password",value = "用户密码")
    private String password;
}
1
2
3
4
5
6
7
8
9
10
@ApiIgnore:使用该注解忽略这个API
//    @ApiOperation(value = "跳转到用户登录页面",notes = "当访问项目根路径的时候,跳转到用户登录页面")
@ApiIgnore
@GetMapping("/")
public String login(){
    return "login";
}
1
2
3
4
5
6
完整接口代码

@Api(tags = "用户模块")
@RestController
@RequestMapping("/user")
public class UserController extends WebMvcConfigurationSupport {
    
    //这个只是模拟存在用户数据,可以忽略
    private Map<Long,User> users = Collections.synchronizedMap(new HashMap<>());

//    @ApiOperation(value = "跳转到用户登录页面",notes = "当访问项目根路径的时候,跳转到用户登录页面")
    @ApiIgnore
    @GetMapping("/")
    public String login(){
        return "login";
    }

    @ApiOperation(value="更新用户详细信息", notes="根据url的id来指定更新对象,并根据传过来的user信息来更新用户详细信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "用户ID", required = true, dataType = "Long"),
            @ApiImplicitParam(name = "user", value = "用户详细实体user", required = true, dataType = "User")
    })
    @PutMapping("/{id}")
    public String putUser(@PathVariable Long id, @RequestBody User user) {
        User u = new User();
        users.put(id, u);
        return "success";
    }

    @ApiResponses({
            @ApiResponse(code = 404,message = "请求路径找不到"),
            @ApiResponse(code = 400,message = "请求参数不正确")
    })
    @ApiOperation(value="创建用户", notes="根据User对象创建用户")
    @ApiImplicitParam(name = "user", value = "用户详细实体user", required = true, dataType = "User")
    @PostMapping("/insert")
    public String postUser(@RequestBody User user) {
        users.put(user.getId(), user);
        return "success";
    }

    @ApiResponses({
            @ApiResponse(code = 404,message = "请求路径找不到"),
            @ApiResponse(code = 400,message = "请求参数不正确")
    })
    @ApiOperation(value="获取用户详细信息", notes="根据url的id来获取用户详细信息")
    @ApiImplicitParam(name = "id", value = "用户ID", required = true, dataType = "Long")
    @GetMapping("/{id}")
    public User getUser(@PathVariable Long id) {
        return users.get(id);
    }

    @ApiOperation(value="删除用户", notes="根据url的id来指定删除对象")
    @ApiImplicitParam(name = "id", value = "用户ID", required = true, dataType = "Long")
    @DeleteMapping("/{id}")
    public String deleteUser(@PathVariable("id") Long id) {
        users.remove(id);
        return "success";
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
6.Swagger2 API文档浏览地址
当上面的配置都没问题之后,就启动SpringBoot项目,访问下面地址,其中的端口改为项目的端口即可。
http://localhost:8080/swagger-ui.html


7.将Swagger2 API接口导入Postman


在导入页面输入该地址:http://localhost:8080/v2/api-docs。
Swagger2所有的API接口都成功导入了postman中了,这样非常方便我们测试

SpringBoot集成Swagger2源码地址
————————————————
版权声明:本文为CSDN博主「Java旅途者」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/weixin_44176169/article/details/105054927

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

AI周红伟

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值