依赖
implementation 'org.springdoc:springdoc-openapi-ui:1.2.3'
使用
- springdoc-openapi-ui作为springboot的组件,几乎全部使用注解进行配置,与swagger2不同的是较好依赖之后不用写任何配置文件,直接生效
- 在线文档访问页面地址为(/v3/api-docs地址是组件生成的json的地址):
http://host:port/swagger-ui/index.html?url=/v3/api-docs
springdoc:
api-docs:
enabled: true
注解说明
@OpenAPIDefinition(
info = @Info(
title = "标题",
version = "1.0",
description = "描述信息"
),
externalDocs = @ExternalDocumentation(description = "参考文档",
url = "https://github.com/swagger-api/swagger-core/wiki/Swagger-2.X---Annotations"
)
)
- @OpenAPIDefinition在springboot之中只会生效一个,用于描述该服务的全局信息
@RestController
@Tag(name = "HelloController")
public class HelloController {
@GetMapping("/hello2")
public String hello2() {
return "hello world v3";
}
}
- @Tag可以加在类和方法上,swagger2中controller会自动加上,用来在页面中显示某个接口属于某个controller,在这里需要手动加上
@Operation(summary = "测试登录的接口",
description = "描述的文字",
responses = {
@ApiResponse(description = "登录信息",
content = @Content(mediaType = "application/json",
schema = @Schema(implementation = UserModel.class))),
@ApiResponse(responseCode = "400", description = "返回400时候错误的原因")},
security = @SecurityRequirement(name = "需要认证"))
@GetMapping("/login")
public UserModel login(
@Parameter(description = "用户名")
@RequestParam(value = "username", required = false) String username,
@Parameter(description = "密码")
@RequestParam(value = "password") String password) {
UserModel userModel = new UserModel();
userModel.setUsername(username);
userModel.setPassword(password);
return userModel;
}
- 接口的注解@Operation,主要用来描述一些接口的信息
- @Parameter用来描述一些传入参数的信息,但是我个人不建议使用这种方式
@Operation(summary = "swagger v3 信息全部写头上", description = "描述的文字",
parameters = {
@Parameter(name = "auth", description = "请求头", in = ParameterIn.HEADER),
@Parameter(name = "id", description = "id", in = ParameterIn.PATH),
@Parameter(name = "param", description = "参数"),
},
responses = {@ApiResponse(responseCode = "400", description = "400错误")},
security = @SecurityRequirement(name = "需要认证"))
@GetMapping("/param/{id}")
public String param(HttpServletRequest httpServletRequest,
@RequestParam(value = "param") String param,
@PathVariable(value = "id") String id) {
String auth = httpServletRequest.getHeader("auth");
return "查看参数: " + auth;
}
- 这种方式则是把参数都放在了 @Operation之中,in可以指定参数来源
@Data
@Schema(name="UserModel", description="用户model")
public class UserModel {
@Schema(description = "用户名")
private String username;
@Schema(description="密码")
private String password;
}
- @Schema可以注解实体类,swagger页面上显示实体类的信息
网友评论