首页 > 编程语言 > 详细

springboot集成swagger

时间:2021-06-05 17:46:51      阅读:10      评论:0      收藏:0      [点我收藏+]

集成 Swagger 管理 API 文档

1)项目中集成 Swagger

集成 Swagger 我们使用封装好了的 Starter 包,代码如下所示。

<!-- Swagger -->
<dependency>
    <groupId>com.spring4all</groupId>
    <artifactId>swagger-spring-boot-starter</artifactId>
    <version>1.7.1.RELEASE</version>
</dependency>

在启动类中使用 @EnableSwagger2Doc 开启 Swagger,代码如下所示。

  1. @EnableSwagger2Doc
  2. @SpringBootApplication
  3. public class AuthApplication {
  4. public static void main(String[] args) {
  5. SpringApplication.run(AuthApplication.class, args);
  6. }
  7. }

2)使用 Swagger 生成文档

Swagger 是通过注解的方式来生成对应的 API,在接口上我们需要加上各种注解来描述这个接口,关于 Swagger 注解的使用在教程后面会有详细讲解,本节只是带大家快速使用 Swagger,使用方法代码如下所示。

  1. @ApiOperation(value = "新增用户")
  2. @ApiResponses({ @ApiResponse(code = 200, message = "OK", response = UserDto.class) })
  3. @PostMapping("/user")
  4. public UserDto addUser(@RequestBody AddUserParam param) {
  5. System.err.println(param.getName());
  6. return new UserDto();
  7. }

参数类定义代码如下所示。

  1. @Data
  2. @ApiModel(value = "com.biancheng.auth.param.AddUserParam", description = "新增用户参数")
  3. public class AddUserParam {
  4. @ApiModelProperty(value = "ID")
  5. private String id;
  6. @ApiModelProperty(value = "名称")
  7. private String name;
  8. @ApiModelProperty(value = "年龄")
  9. private int age;
  10. }

在线测试接口

接口查看地址可以通过服务地址 /swagger-ui.html 来访问,见图 1。

技术分享图片
图 1  swagger 主页


可以展开看详情,见图 2。

技术分享图片
图 2  swagger 接口主页


在 param 中输入参数,点击 Try it out 按钮可以调用接口,见图 3。

技术分享图片
图 3  swagger 接口调用结果

springboot集成swagger

原文:https://www.cnblogs.com/chenTo/p/14852956.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!