Swagger使用

一、Swagger介绍

Swagger是一个用于设计、构建、编写和使用RESTful API的工具集合。它允许您通过将API文档与API代码相结合来自动为API生成文档,从而提高了API的可读性和可用性。

二、使用教程

1.导入依赖

<!--knife4j依赖,用来操作swagger-->
<dependency>
   <groupId>com.github.xiaoymin</groupId>
   <artifactId>knife4j-spring-boot-starter</artifactId>
   <version>3.0.2</version>
</dependency>

2.导入knife4j相关配置

@Configuration
@EnableSwagger2
@EnableKnife4j
public class WebMvcConfig extends WebMvcConfigurationSupport {
    @Override//设置静态资源映射
    protected void addResourceHandlers(ResourceHandlerRegistry registry) {
        log.info("资管映射开始.........");
        registry.addResourceHandler("doc.html").addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
        registry.addResourceHandler("/backend/**").addResourceLocations("classpath:/backend/");
        registry.addResourceHandler("/front/**").addResourceLocations("classpath:/front/");
    }
    @Bean
    public Docket createRestApi() {
        // 文档类型
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.lx.reggie.controller"))
                .paths(PathSelectors.any())
                .build();
    }
	//描述接口文档
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("蓝朽")
                .version("1.0")
                .description("蓝朽工作室")
                .build();
    }
}

三、Swagger常用注解

在这里插入图片描述

1.@Api

描述API的信息,例如API名称、版本、作者等。

@Api(value = "用户管理", tags = {"用户控制"})
@RestController
@RequestMapping("/users")
public class UserController {

}

2.@ApiOperation

定义API端点的操作,例如名称、描述、请求方式、参数等。其中,value参数代表API操作名称,notes参数代表API操作描述信息。

@Api(value = "用户管理", tags = {"用户控制"})
@RestController
@RequestMapping("/users")
public class UserController {
    @ApiOperation(value = "根据用户ID查询用户信息", notes = "查询用户信息")
    @GetMapping("/{userId}")
    public User getUserById(@PathVariable Integer userId) {
        return userService.getUserById(userId);
    }
}

3.@ApiModel

描述实体模型,例如Model对象的名称、字段属性名、数据类型等。

@ApiModel(value = "用户实体类")
public class User {

    @ApiModelProperty(value = "用户ID", required = true)
    private Integer id;

    @ApiModelProperty(value = "用户名", required = true)
    private String username;

    @ApiModelProperty(value = "密码", required = true)
    private String password;

    @ApiModelProperty(value = "邮箱", required = true)
    private String email;
    // ...
}

4.@ApiModelProperty

给Model类属性添加注释描述。

@ApiModel(value = "用户实体类")
public class User {

    @ApiModelProperty(value = "用户ID", required = true)
    private Integer id;

    @ApiModelProperty(value = "用户名", required = true)
    private String username;

    @ApiModelProperty(value = "密码", required = true)
    private String password;

    @ApiModelProperty(value = "邮箱", required = true)
    private String email;

}

5.@ApiImplicitParams和 @ApiImplicitParam

@ApiImplicitParams:用在请求的方法上,表示一组参数说明
@ApiImplicitParam:用在@ApilmplicitParams注解中,指定一个请求参数的各个方面

 	@ApiOperation("套餐分页查询")
    @ApiImplicitParams({
            @ApiImplicitParam(name="page",value = "页码",required = true),
            @ApiImplicitParam(name="pageSize",value = "每页显示多少数据",required = true),
            @ApiImplicitParam(name="name",value = "套餐名称",required = false),
    })
    @GetMapping("/page")//套餐分页查询
    public R<Page> page(int page,int pageSize,String name){
        //分页构造器
        Page<Setmeal> pageInfo  =new Page<>(page,pageSize);
        Page<SetmealDto> dtoPage = new Page<>();
        //条件构造器
        LambdaQueryWrapper<Setmeal> lqw = new LambdaQueryWrapper<>();
        //根据name进行like查询
        lqw.like(name!=null,Setmeal::getName,name);
        //添加排序条件,根据更新时间降序排序
        lqw.orderByDesc(Setmeal::getUpdateTime);
        setmealService.page(pageInfo, lqw);
        //对象拷贝
        BeanUtils.copyProperties(pageInfo,dtoPage,"records");
        List<Setmeal> records = pageInfo.getRecords();
        List<SetmealDto> list = records.stream().map((item)->{
            SetmealDto setmealDto = new SetmealDto();
            BeanUtils.copyProperties(item,setmealDto);
            //分类id
            Long categoryId = item.getCategoryId();
            //根据id查询分类对象
            Category category = categoryService.getById(categoryId);
            if (category != null) {
                //分类名称
                String name1 = category.getName();
                setmealDto.setCategoryName(name1);
            }
            return setmealDto;
        }).collect(Collectors.toList());
        dtoPage.setRecords(list);
        return R.success(dtoPage);
    }

6.@ApiIgnore

用于忽略不需要生成API文档的接口或参数。

@Api(value = "用户管理", tags = {"用户控制"})
@RestController
@RequestMapping("/users")
public class UserController {
    @ApiIgnore
    @GetMapping("/health")
    public String healthCheck() {
        return "OK";
    }
  
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

蓝朽

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

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

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

打赏作者

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

抵扣说明:

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

余额充值