Swagger的入门和常用注解

项目中引入swagger所需的依赖

在启动项上添加允许Swagger的注解@EnableSwagger2

@EnableSwagger2
@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class})
public class EpgLanucherApplication {
    public static void main(String[] args) {
        //System.setProperty("spring.devtools.restart.enabled", "false");
        SpringApplication.run(EpgLanucherApplication.class, args);
        System.out.println("(♥◠‿◠)ノ゙ 门户后台管理系统启动成功   ლ(´ڡ`ლ)゙  ");
    }
}

在所需的Controller类上添加@Api

@Api(value="xx",tags="2xx"), value是当前controller的描述, tags也可以作为描述, 也可以把controller分为几组.

@Api(tags = {"对外接口-controller","对内接口-controller"})
@Controller
@RequestMapping("/api/epg")

效果:

方法上加注解 @ApiOperation(value="Redis测试")

等同于告诉Swagger这个方法的作用描述

效果同上图的方法描述

方法隐式的参数说明注解@ApiImplicitParam

name 参数名称

value 参数描述

required 是否必填

dataType 参数数据类型

paramType 参数类型

 @ApiOperation("获取用户详细")
    @ApiImplicitParam(name = "userId", value = "用户ID", required = true, dataType = "int", paramType = "path")
    @GetMapping("/{userId}")
    public AjaxResult getUser(@PathVariable Integer userId) {
        if (!users.isEmpty() && users.containsKey(userId)) {
            return AjaxResult.success(users.get(userId));
        } else {
            return error("用户不存在");
        }
    }

效果⬇

方法参数加描述信息@ApiParam

name 这个参数名称是什么, 一般不填写. 默认就是参数名称

value 请求参数的描述信息

required 请求参数为必填项

 
 
@ApiOperation(value = "获取父code为当前code的所有实例")
@GetMapping("/getExampleSon")
@ResponseBody
public String getExampleSon(@ApiParam(value = "父类Code",required = true ) String parentCode){
return epgService.getExampleByRedis(parentCode);
}
 

效果⬇

方法参数为对象时,需要在对象类中加入注解 @ApiModel, @ApiModelProperty

ApiModel 表示对类作为说明,用于参数为实体类接收.

ApiModeProperty 用于对象的方法字段的描述.

name 表示字段名,一般不写

value 表示字段的说明

required 请求参数为必填项

hidden 表示字段是否隐藏

@ApiModel("用户实体")
class UserEntity {
    @ApiModelProperty("用户ID")
    private Integer userId;

    @ApiModelProperty("用户名称")
    private String username;

    @ApiModelProperty("用户密码")
    private String password;

    @ApiModelProperty("用户手机")
    private String mobile;

效果⬇

暂时先记录这么多, 之后用到别的再新增.

猜你喜欢

转载自www.cnblogs.com/shansm/p/12924749.html