Swagger在线文档使用教程

1|0springboot整合Swagger2

1、首先创建一个springboot工程,在pom文件内导入依赖

  <!--swagger依赖-->
      <!--Swagger2-->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.9.0</version>
        </dependency>
        <!--Swagger-ui界面-->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.9.0</version>
        </dependency>

2、在springboot工程内的项目运行无误后,创建配置类SwaggerConfig

 @Configuration // 配置类
 @EnableSwagger2 // 开启Swagger2
 public class SwaggerConfig {
 
   /**
    * 配置了Swagger的Docket的Bean实例
    * 可以有多个
    * @return
    */
   @Bean
   public Docket docket(Environment environment) {
     // 获取项目环境
     // 设置要显示的Swagger2环境
     Profiles profiles = Profiles.of("dev");
     // 监听   通过environment.acceptsProfiles判断是否处在自己设定的环境
     boolean flag = environment.acceptsProfiles(profiles);
 
     return new Docket(DocumentationType.SWAGGER_2)
        .apiInfo(apiInfo())
         // Select a spec默认值
        .groupName("茶碗儿")
         // 是否开启swagger2
         // .enable(false)
         // 监听
        .enable(flag)
        .select()
         // RequestHandlerSelectors   配置要扫描接口的方式
         // basePackage               指定扫描的包
         // any                       扫描全部
         // none                     不扫描
         // withClassAnnotation       扫描类上的注解,参数是一个注解的反射对象
         // withMethodAnnotation     扫描方法上的注解
        .apis(RequestHandlerSelectors.basePackage("com.changgou.controller"))
         // 过滤路径
         // .paths(PathSelectors.ant("/changgou/**"))
        .build();
  }
 
   @Bean
   public Docket docket1(Environment environment) {
     return new Docket(DocumentationType.SWAGGER_2)
            .groupName("花生糖");
  }
 
   // 配置Swagger2信息
   private ApiInfo apiInfo() {
     // 作者信息
     Contact contact = new Contact("茶碗儿", "https://www.cnblogs.com/chawaner/", "*******@qq.com");
 
     return new ApiInfo(
         // 大标题
         "畅购商城",
         // 描述
         "畅购商城在线API",
         // 版本
         "v1.0",
         // 服务组织url
         "https://www.cnblogs.com/chawaner/",
         // 作者信息
         contact,
         // 开源版本号
         "Apache 2.0",
         //// 开源版本url
         "http://www.apache.org/licenses/LICENSE-2.0",
         new ArrayList<VendorExtension>());
  }
 }

3、在JavaBean中加上注解

 @ApiModel(description = "Result", value = "Result")
 @Data // lombok注解
 public class Result<T> implements Serializable {
 
   @ApiModelProperty(value = "执行是否成功,true:成功,false:失败", required = true)
   private boolean flag; // 是否成功
 
   @ApiModelProperty(value = "返回状态码,20000:成功,20001:失败,20002:用户名或密码错误,20003:权限不足,20004:远程调用失败,20005:重复操作,20006:没有对应的抢购数据", required = true)
   private Integer code; // 返回码
 
   @ApiModelProperty(value = "提示信息", required = true)
   private String message; // 返回消息
 
   @ApiModelProperty(value = "逻辑数据", required = true)
   private T data; // 返回数据
 
   public Result(boolean flag, Integer code, String message, Object data) {
     this.flag = flag;
     this.code = code;
     this.message = message;
     this.data = (T) data;
  }
 
   public Result(boolean flag, Integer code, String message) {
     this.flag = flag;
     this.code = code;
     this.message = message;
  }
 
   public Result() {
     this.flag = true;
     this.code = StatusCode.OK;
     this.message = "操作成功!";
  }
 }

4、在controller类中加入注解

 @Api(
     value = "用户品牌操作",
     tags = {"用户品牌操作接口"})
 @RestController
 @RequestMapping(value = "/brand")
 @CrossOrigin // 跨域访问:域名、端口、协议不一致
 public class BrandController {
 
   @Autowired private BrandService brandService;
 
   /** 查询所有 */
   @ApiOperation("查询所有品牌信息")
   @GetMapping
   public Result<List<Brand>> findAll() {
     // 查询所有品牌信息
     List<Brand> brands = brandService.findAll();
     // 响应结果封装
     return new Result<List<Brand>>(true, StatusCode.OK, "查询品牌集合成功!", brands);
  }
 
   /** 根据主键id查询 */
   @ApiOperation("据主键id查询") // 接口 放在方法上
   @GetMapping(value = "/{id}")
   public Result<Brand> findById(
       @ApiParam(value = "传入的id") @PathVariable(value = "id") Integer id) {
     Brand brand = brandService.findById(id);
     return new Result<Brand>(true, StatusCode.OK, "根据id查询品牌成功!", brand);
  }
 
   /**
    * 增加品牌
    *
    * @param brand
    */
   @ApiOperation("增加品牌")
   @PostMapping
   public Result add(@ApiParam(value = "要增加的品牌信息") @RequestBody Brand brand) {
     brandService.add(brand);
     return new Result(true, StatusCode.OK, "添加品牌成功!");
  }
 
   /**
    * 根据ID修改品牌数据
    *
    * @param id
    * @param brand
    * @return
    */
   @ApiOperation("根据ID修改品牌信息")
   @PutMapping(value = "/{id}")
   public Result update(
       @ApiParam(value = "输入的id", example = "1") @PathVariable(value = "id") Integer id,
       @ApiParam(value = "brand") @RequestBody Brand brand) {
     brand.setId(id);
     brandService.update(brand);
     return new Result(true, StatusCode.OK, "根据ID修改品牌成功!");
  }
 
   /**
    * 根据ID删除品牌数据
    *
    * @param id
    */
   @ApiOperation("根据ID删除品牌")
   @DeleteMapping(value = "/{id}")
   public Result delete(@ApiParam(value = "输入的id") @PathVariable(value = "id") Integer id) {
     brandService.delete(id);
     return new Result(true, StatusCode.OK, "根据ID删除品牌数据成功!");
  }
 
   /** 根据品牌信息多条件搜索 */
   @ApiOperation("根据品牌信息多条件搜索")
   @PostMapping(value = "/search")
   public Result<List<Brand>> findList(@ApiParam(value = "查询条件") @RequestBody Brand brand) {
     List<Brand> brands = brandService.findList(brand);
     return new Result<List<Brand>>(true, StatusCode.OK, "根据品牌信息多条件搜索成功!", brands);
  }
 
   /**
    * 分页查询实现
    *
    * @param page:当前页
    * @param size:每页显示条数
    * @return
    */
   @ApiOperation("分页查询实现")
   @GetMapping(value = "/search/{page}/{size}")
   public Result<PageInfo<Brand>> findPage(
       @ApiParam(value = "当前页") @PathVariable(value = "page") Integer page,
       @ApiParam(value = "显示的条数") @PathVariable(value = "size") Integer size) {
     PageInfo<Brand> pageInfo = brandService.findPage(page, size);
     return new Result<PageInfo<Brand>>(true, StatusCode.OK, "分页查询成功!", pageInfo);
  }
 
   /**
    * 分页查询 + 条件搜索
    *
    * @param brand:搜索条件
    * @param page:当前页
    * @param size:每页显示条数
    * @return
    */
   @ApiOperation("分页查询 + 条件搜索")
   @PostMapping(value = "/search/{page}/{size}")
   public Result<PageInfo<Brand>> findPage(
       @ApiParam(value = "查询条件") @RequestBody Brand brand,
       @ApiParam(value = "当前页") @PathVariable(value = "page") Integer page,
       @ApiParam(value = "显示的条数") @PathVariable(value = "size") Integer size) {
     PageInfo<Brand> pageInfo = brandService.findPage(brand, page, size);
     return new Result<PageInfo<Brand>>(true, StatusCode.OK, "分页查询成功!", pageInfo); 

}

5、配置文件application.yml中配端口号和端口扫描

 注意:
 1.端口号是从浏览器打开swagger-ui时的端口
 2.配置端口扫描是为了设置在开发时开启swagger在线文档,在产品发布后不开启
 3.注意看上面的SwaggerConfig配置类里面的:Profiles profiles = Profiles.of("dev");
 扫描包含dev的配置文件,所以打开ui界面就得18082端口

application.yml

 #端口的配置
 server:
   port: 18081
       
 #设置对dev的端口开启swagger
 #本来是访问http://localhost:18081/swagger-ui.html打开swagger-ui界面
 #配置了这个之后,打开swagger-ui界面就要访问http://localhost:18082/swagger-ui.html
 spring:
   profiles:
     active: dev

application-dev.yml

 server:
   port: 18082

application-pro.yml

 server:
   port: 18083

6、Swagger常用注解

位置注解说明
controller @Api 对请求类的说明
方法 @ApiOperation 方法的说明
方法 @ApiImplicitParams、@ApiImplicitParam 方法的参数的说明;@ApiImplicitParams 用于指定单个参数的说明
方法 @ApiResponses、@ApiResponse 方法返回值的说明 ;@ApiResponses 用于指定单个参数的说明
对象 @ApiModel 用在JavaBean类上,说明JavaBean的 用途
对象 @ApiModelProperty 用在JavaBean类的属性上面,说明此属性的的含议

@Api:

@Api:放在 请求的类上,与 @Controller 并列,说明类的作用,如用户模块,订单类等。 tags="说明该类的作用" value="该参数没什么意义,所以不需要配置"

示例

@Api(tags="订单模块") @Controller public class OrderController { }

@Api其他属性配置:

属性名称备注
value url的路径值
tags 如果设置这个值、value的值会被覆盖
description 对api资源的描述
basePath 基本路径
position 如果配置多个Api 想改变显示的顺序位置
produces 如, “application/json, application/xml”
consumes 如, “application/json, application/xml”
protocols 协议类型,如: http, https, ws, wss.
authorizations 高级特性认证时配置
hidden 配置为true ,将在文档中隐藏

@ApiOperation:

@ApiOperation:"用在请求的方法上,说明方法的作用" value="说明方法的作用" notes="方法的备注说明"

@ApiImplicitParams、@ApiImplicitParam:方法参数的说明

@ApiImplicitParams:用在请求的方法上,包含一组参数说明 @ApiImplicitParam:对单个参数的说明 name:参数名 value:参数的说明、描述 required:参数是否必须必填 paramType:参数放在哪个地方 · query --> 请求参数的获取:@RequestParam · header --> 请求参数的获取:@RequestHeader · path(用于restful接口)--> 请求参数的获取:@PathVariable · body(请求体)--> @RequestBody User user · form(普通表单提交) dataType:参数类型,默认String,其它值dataType="Integer" defaultValue:参数的默认值

示例:

@Api(tags="用户模块") @Controller public class UserController { @ApiOperation(value="用户登录",notes="随边说点啥") @ApiImplicitParams({ @ApiImplicitParam(name="mobile",value="手机号",required=true,paramType="form"), @ApiImplicitParam(name="password",value="密码",required=true,paramType="form"), @ApiImplicitParam(name="age",value="年龄",required=true,paramType="form",dataType="Integer") }) @PostMapping("/login") public JsonResult login(@RequestParam String mobile, @RequestParam String password, @RequestParam Integer age){ //... return JsonResult.ok(map); } }

@ApiResponses、@ApiResponse:方法返回值的状态码说明

@ApiResponses:方法返回对象的说明 @ApiResponse:每个参数的说明 code:数字,例如400 message:信息,例如"请求参数没填好" response:抛出异常的类

示例:

@Api(tags="用户模块") @Controller public class UserController { @ApiOperation("获取用户信息") @ApiImplicitParams({ @ApiImplicitParam(paramType="query", name="userId", dataType="String", required=true, value="用户Id") }) @ApiResponses({ @ApiResponse(code = 200, message = "请求成功"), @ApiResponse(code = 400, message = "请求参数没填好"), @ApiResponse(code = 404, message = "请求路径没有或页面跳转路径不对") }) @ResponseBody @RequestMapping("/list") public JsonResult list(@RequestParam String userId) { ... return JsonResult.ok().put("page", pageUtil); } }

@ApiModel:用于JavaBean上面,表示对JavaBean 的功能描述

@ApiModel的用途有2个: 当请求数据描述,即 @RequestBody 时, 用于封装请求(包括数据的各种校验)数据; 当响应值是对象时,即 @ResponseBody 时,用于返回值对象的描述。

 


__EOF__

本文作者茶碗儿
本文链接https://www.cnblogs.com/chawaner/p/13894563.html
关于博主:评论和私信会在第一时间回复。或者直接私信我。
版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!
声援博主:如果您觉得文章对您有帮助,可以点击文章右下角推荐一下。您的鼓励是博主的最大动力!
posted @   茶碗儿  阅读(629)  评论(0编辑  收藏  举报
编辑推荐:
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
阅读排行:
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
点击这里跳转到-->【茶碗儿CSDN】
点击右上角即可分享
微信分享提示