Integrating Knife4j with Spring Boot for Enhanced Swagger API Documentation
This article introduces Knife4j, a lightweight Java MVC Swagger enhancement, explains its core features and UI improvements, and provides a step‑by‑step guide with Maven dependencies, configuration classes, model definitions, and controller code to quickly set up interactive API documentation in a Spring Boot project.
Knife4j is a lightweight enhancement for Java MVC frameworks that integrates Swagger to generate API documentation, offering a compact, powerful UI compared to the original swagger‑bootstrap‑ui.
The project’s main modules are listed and its source code is hosted on GitHub (https://github.com/xiaoymin/swagger-bootstrap-ui) and Gitee (https://gitee.com/xiaoym/knife4j).
Its core functions include detailed documentation (interface address, request/response examples, parameters, status codes) and an online debugging feature that parses request parameters, validates forms, and displays response data, headers, curl commands, response time, and status.
Additional UI enhancements comprise personalized configuration, offline markdown documentation generation, and interface sorting for step‑wise API operations.
To get started, add the following Maven dependency:
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>knife4j-spring-boot-starter</artifactId>
<version>1.9.6</version>
</dependency>Create a Swagger configuration class similar to the standard Swagger setup, adding the @EnableSwaggerBootstrapUi annotation:
@Configuration
@EnableSwagger2
@EnableSwaggerBootstrapUi
public class Swagger2Config {
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.useDefaultResponseMessages(false)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("spring.boot.knife4j.controller"))
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("项目接口文档")
.description("服务相关接口")
.contact(new Contact("vincent", null, "[email protected]"))
.version("1.0")
.build();
}
}Define common response and data models:
@ApiModel("通用接口返回对象")
@AllArgsConstructor
@NoArgsConstructor
@Data
public class Results
{
@ApiModelProperty(required = true, notes = "结果码", example = "200")
private int state;
@ApiModelProperty(required = true, notes = "时间戳", example = "1567425139000")
private long time;
@ApiModelProperty(required = true, notes = "返回信息", example = "SUCCESS")
private String message;
@ApiModelProperty(required = true, notes = "返回数据", example = "{\"name\":\"blues\"}")
private T content;
}
@ApiModel("用户对象")
@AllArgsConstructor
@NoArgsConstructor
@Data
public class UserVO {
@ApiModelProperty(required = true, notes = "用户名", example = "blues")
private String name;
@ApiModelProperty(required = true, notes = "用户返回消息", example = "hello world")
private String words;
}Implement a sample controller with full Swagger annotations:
@Api(tags = "HELLO CONTROLLER 测试功能接口")
@RestController
public class HelloController {
@ApiImplicitParams({
@ApiImplicitParam(name = "name", value = "用户名称", required = true, dataType = "String", paramType = "path", example = "blues")
})
@ApiResponses({
@ApiResponse(code = 200, message = "接口返回成功状态"),
@ApiResponse(code = 500, message = "接口返回未知错误,请联系开发人员调试")
})
@ApiOperation(value = "Hello 测试接口", notes = "访问此接口,返回hello语句,测试接口")
@GetMapping("hello/{name}")
public Results
hello(@PathVariable String name) {
UserVO userVO = new UserVO(name, "hello " + name);
Results
results = new Results<>(200, "SUCCESS", userVO);
return results;
}
}After restarting the application, the documentation is accessible at http://localhost:8080/doc.html?plus=1 , showing a left‑side navigation with the new controller, detailed request/response information, and an interactive testing panel.
The UI also supports global parameters (e.g., JWT tokens) and various personalization settings, making Knife4j a more user‑friendly alternative to the original Swagger UI.
Overall, Knife4j provides a seamless way to enhance Swagger documentation in Spring Boot projects with richer UI features and built‑in debugging capabilities.
Selected Java Interview Questions
A professional Java tech channel sharing common knowledge to help developers fill gaps. Follow us!
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.