Swagger学习
注:这是我写的第一篇博客,试试水,只是自己的学习总结,不是教程。
SpringBoot集成swagger3.0
新建一个config包
添加@configuration和@Bean注释
写一个Docket实例
Config包
@Configuration
//@EnableSwagger2
public class Swagger {
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.groupName("SuperGame")
.select()
.apis(RequestHandlerSelectors.basePackage("com.itheima.controller"))//扫描controller包
//.paths(PathSelectors.any()) //不扫描任何路径
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("SwaggerUI演示")
.description("ljd-swagger")
.contact(new Contact("supergame", null, null))
.version("1.0")
.build();
}
}
Controller
@PostMapping("/Insert")
@ResponseBody
@ApiOperation(value="插入用户",notes="插入一个用户")
@ApiResponse(responseCode = "404", description = "Employee not found")
public String InsertUser(@RequestBody User user){
System.out.println("ok3");
int result= service1.InsertUser(user);
System.out.println(result);
System.out.println("ok4");
return "Insert into OK";
}
User实体类
@Data
@ApiModel("用户实体类")
public class User {
private Integer id;
@ApiModelProperty(value="姓名") //用Inter类型上多写一个example
private String name;
private double money;
}
效果
访问:http://localhost:8080/swagger-ui/
总结
1.注释
@Api:用在controller类,描述API接口
@ApiOperation(value="",note="")用在接口上,也就是Controller类的方法上
@ApiModel("") :描述对象 用在实体类上,例如User
@ApiModelProperty(value="") 用来实体类的具体字段上
@Api(tags = “”) Controller类前使用
@ApiResponses:描述接口响应
@ApiParam()在Swagger3.0使用有些问题
2.Docket实例
构建Docket时通过 select()
方法配置扫描接口。Docket的完整代码如下:
@Bean
public Docket docket(Environment environment){
return new Docket(DocumentationType.OAS_30)
.apiInfo(apiInfo())
// 配置Api文档分组
.groupName("TIOXY")
// enable()是否启用Swagger,默认是true
.enable(flag)
.select()
// RequestHandlerSelectors,配置要扫描接口的方式
// basePackage指定要扫描的包
// any()扫描所有,项目中的所有接口都会被扫描到
// none()不扫描
// withClassAnnotation()扫描类上的注解
// withMethodAnnotation()扫描方法上的注解
.apis(RequestHandlerSelectors.basePackage("com.tioxy.controller"))
// paths()过滤某个路径
.paths(PathSelectors.any())
.build();
}
groupName("TIOXY")
:表示此Docket实例的名字,也就是接口文档页面右上角选择的实例名,实际开发中我们是多人开发,对应的就是多个Docket实例enable(flag)
:enable()
是否启用Swagger,默认是true
参考链接
http://c.biancheng.net/view/5533.html
https://blog.csdn.net/weixin_49527334/article/details/109510858