Swagger 使用笔记
Swagger是一个规范且完整的框架,使用简单的几个注解,就可以生成Restful风格的在线接口文档,还能在线测试接口。
SpringBoot集成Swagger
新建一个springboot项目,然后在pom.xml文件中添加maven依赖。
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
<!-- 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>
编写配置类
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket docket(Environment environment) {
// application.yml中启用的是 dev 配置才开启swagger文档
Profiles profiles = Profiles.of("dev");
boolean enable = environment.acceptsProfiles(profiles);
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo()) // 基本信息
.enable(enable) // 是否开启
.select()
.apis(RequestHandlerSelectors.basePackage("com.xx.xx")) // 扫描的包
.build()
//.securitySchemes(securitySchemes()) // 结合spingsecurity使用需要配置
//.securityContexts(securityContexts() // 结合spingsecurity使用需要配置
);
}
@Bean
public ApiInfo apiInfo() {
Contact contact = new Contact("联系人", "联系人访问链接", "联系人邮箱");
return new ApiInfo("项目名",
"",
"版本号",
"组织链接",
contact,
"", // 许可
"", // 许可链接
new ArrayList<>()
);
}
}
开始使用
在控制器类上添加注解@Api
@Api(tags = "城市管理")
@RestController
@RequestMapping("city")
public class CityController {
}

在方法上添加注解@ApiOperation
@ApiOperation(value = "更新部门信息")
@ApiImplicitParams({
@ApiImplicitParam(name = "id", value = "部门ID", required = true, dataType = "String"),
@ApiImplicitParam(name = "type", value = "部门", required = false, dataType = "String"),
@ApiImplicitParam(name = "remark", value = "备注", required = false, dataType = "String"),
})
@PostMapping("update")
public ResultData<Dept> update(Dept dept) throws DefineException {
return new ResultData<>(ResultCode.SUCCESS, "部门信息更新成功", deptService.update(dept));
}

点击Try it out,填入必填参数,再点击Execute按钮直接调用方法
在模型类上添加字段注解
@Data
public class Country {
@ApiModelProperty("id")
private Integer id;
@ApiModelProperty("城市编码")
private String code;
@ApiModelProperty("城市名称")
private String name;
@ApiModelProperty("单位")
private String unit;
}
在swagger的Responses模块可以看到注释

SpringSecurity 相关的内容后续再补充。

浙公网安备 33010602011771号