由于目前工作项目写的接口越来越多了,为了能够更加方便地优化接口,以及整理接口文档,所以就考虑引入接口文档生成工具。目前的接口文档生成工具被提及较多的是Swagger,经过了引入尝试后,Swagger是比较轻松地就被引入了。但是Swagger页面属实是难以恭维,比较简单但是不美观。于是经过我再一轮的技术调研后,我发现了一个国产的技术框架——Knife4j,Knife4j是结合了Swagger,并在此基础上更精致了页面的一项技术。接下来我将以springboot2和3的环境中分别介绍,讲述如何在Springboot中引入Knife4j。
<dependency>
<groupId>com.github.xiaoymingroupId>
<artifactId>knife4j-spring-boot-starterartifactId>
<version>3.0.3version>
dependency>
@EnableOpenApi
@SpringBootApplication
@MapperScan("com.example.mapper")
public class DemoApplication {
public static void main(String[] args) {
//SpringApplication.run(DemoApplication.class, args);
new SpringApplicationBuilder(DemoApplication.class).run(args);
}
}
@Configuration
@EnableSwagger2
//下面两条是Knife4j引入的,若是只用Swagger可去掉
@EnableKnife4j
@Import(BeanValidatorPluginsConfiguration.class)
public class SwaggerConfig {
/**
* Swagger配置 for Knife4j
* @return
*/
@Bean(value = "defaultApi2")
public Docket defaultApi2() {
Docket docket=new Docket(DocumentationType.SWAGGER_2)
.apiInfo(
new ApiInfoBuilder()
// 文档标题
.title("title")
// 文档描述信息
.description("content")
.contact(new Contact("peng_YunJun","https://blog.csdn.net/peng_YuJun?type=blog","[email protected]"))
// 文档版本号
.version("1.0")
.build()
)
//分组名称
.groupName("Swagger在线文档")
// select():生成 API 文档的选择器,用于指定要生成哪些 API 文档
.select()
//这里指定Controller扫描包路径
.apis(RequestHandlerSelectors.basePackage("com.example.controller"))
// paths():指定要生成哪个 URL 匹配模式下的 API 文档。这里使用 PathSelectors.any(),表示生成所有的 API 文档。
.paths(PathSelectors.any())
.build();
return docket;
}
}
@APi:用在请求的类上,例如Controller,表示对类的说明
@ApiOperation:用在请求的方法上,说明方法的用途、作用
@ApiImplicitParams:用在请求的方法上,表示一组参数说明
@ApiImplicitParam:用在@ApilmplicitParams注解中,指定请求参数的各个方法
@ApiParam:用在请求的类的形参上
@ApiModel:用在类上,通常是实体类,表示一个返回响应数据的信息
@ApiModelProperty:用在属性上,描述响应类的属性
@RestController
@RequestMapping("appointment")
@Api(tags = "Appointment信息请求类")
public class AppointmentController {
/**
* 服务对象
*/
@Resource
private AppointmentService appointmentService;
/**
* 分页查询
* @param currentPage
* @param pageSize
* @param appointment 筛选条件
* @return 查询结果
*/
@ApiOperation(value = "分页查询" notes = "额外说明")
@GetMapping("getPage")
public ResponseData getPage(Integer currentPage, Integer pageSize, Appointment appointment) {
if (currentPage == null || pageSize == null){
return new ResponseData(HttpStatusEnum.BAD_REQUEST.getCode(), HttpStatusEnum.BAD_REQUEST.getMessage());
}
return appointmentService.getByPage(currentPage, pageSize, appointment);
}
/**
* 通过主键查询单条数据
*
* @param id 主键
* @return 单条数据
*/
@ApiOperation("根据ID查询信息")
@GetMapping("findById")
public ResponseData findById(Long id) {
if (id == null){
return new ResponseData(HttpStatusEnum.BAD_REQUEST.getCode(),HttpStatusEnum.BAD_REQUEST.getMessage());
}
return appointmentService.findById(id);
}
}
@ApiModel(value = "ResponseDate",description = "统一前端响应格式")
public final class ResponseData<T> {
@ApiModelProperty(name = "code",value = "响应代码", example = "200")
private Integer code;
@ApiModelProperty(name = "msg",value = "响应信息",example = "添加成功")
private String msg;
@ApiModelProperty(name = "data",value = "响应数据",example = "响应数据/空")
private T data;
}
启动服务,工程启动起来,访问http://localhost:{该服务的端口号}/doc.html查看接口信息和进行测试
com.github.xiaoymin
knife4j-openapi3-jakarta-spring-boot-starter
/** 接口文档生成配置
* 可以通过 /doc.html 访问接口文档
*/
@Configuration
public class SwaggerConfig {
@Bean
public OpenAPI springShopOpenAPI() {
return new OpenAPI()
.info(new Info().title("xxx平台-API接口文档")
//描叙
.description("这是基于Knife4j OpenApi3的接口文档")
//版本
.version("v1.0")
//作者信息,自行设置
.contact(new Contact().name("xxx").email("[email protected]").url("https://www.baidu.com"))
//设置接口文档的许可证信息
.license(new License().name("Apache 2.0").url("http://springdoc.org")))
.externalDocs(new ExternalDocumentation()
.description("xxx平台-主页")
.url("http://127.0.0.1:8080/index"));
}
}
这里与springboot2使用的依赖不一样,Springfox改用Springdoc后,注解改变:
@Api → @Tag
@ApiIgnore → @Parameter(hidden = true) or @Operation(hidden = true) or @Hidden
@ApiImplicitParam → @Parameter
@ApiImplicitParams → @Parameters
@ApiModel → @Schema
@ApiModelProperty(hidden = true) → @Schema(accessMode = READ_ONLY)
@ApiModelProperty → @Schema
@ApiOperation(value = “foo”, notes = “bar”) → @Operation(summary = “foo”, description = “bar”)
@ApiParam → @Parameter
@ApiResponse(code = 404, message = “foo”) → @ApiResponse(responseCode = “404”, description = “foo”)
@RestController
@RequestMapping("api")
@Tag(name = "App接口请求类")
public class AppApiController {
@Resource
private UserService userService = new UserService();
@Operation(summary = "APP登录系统")
@LogAnnotation(info = "APP登录系统", logtypeid = Constants.loginLogTypeId)
@PostMapping("login")
@ResponseBody
public Map<String, Object> login(String phone_num, String password, HttpSession session) {
if (!StringUtils.hasText(phone_num) || !StringUtils.hasText(password)) {
Map<String, Object> resultMap = new HashMap<>();
resultMap.put("code", RequestResultEnum.BAD_REQUEST.getCode());
resultMap.put("msg", RequestResultEnum.BAD_REQUEST.getMessage());
return resultMap;
}
Map<String, Object> map = userService.loginAccount(phone_num, password);
return map;
}
}
@Schema(description = "用户实体")
public class User {
@Schema(description = "用户名称")
private String userName;
@Schema(description = "密码")
private String password;
@Schema(description = "邮箱")
private String email;
@Schema(description = "年龄")
private int age;
//...
}
启动服务,工程启动起来,访问http://localhost:{该服务的端口号}/doc.html查看接口信息和进行测试
因为Swagger无法确定用哪一个get或set方法,所以就会冲突报错。用注解@JsonProperty(“属性名”)可以解决,放置在其中一个get或set方法上,用于指定映射关系。