springboot整合knife4j全过程
作者:qingkong2358103969
这篇文章主要介绍了springboot整合knife4j全过程,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
1.首先引用Knife4j的starter
Maven坐标如下:
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>knife4j-openapi3-jakarta-spring-boot-starter</artifactId>
<version>4.1.0</version>
</dependency>
2.以在配置文件中进行开启
部分配置如下:
# springdoc-openapi项目配置
springdoc:
swagger-ui:
path: /swagger-ui.html
tags-sorter: alpha
operations-sorter: alpha
api-docs:
path: /v3/api-docs
group-configs:
- group: 'default'
paths-to-match: '/**'
packages-to-scan: com.xiaominfo.knife4j.demo.web
# knife4j的增强配置,不需要增强可以不配
knife4j:
enable: true
setting:
language: zh_cn
3.最后使用OpenAPI3的规范注解
注释各个Spring的REST接口
示例代码如下:
@RestController
@RequestMapping("body")
@Tag(name = "body参数")
public class BodyController {
@Operation(summary = "普通body请求")
@PostMapping("/body")
public ResponseEntity<FileResp> body(@RequestBody FileResp fileResp){
return ResponseEntity.ok(fileResp);
}
@Operation(summary = "普通body请求+Param+Header+Path")
@Parameters({
@Parameter(name = "id",description = "文件id",in = ParameterIn.PATH),
@Parameter(name = "token",description = "请求token",required = true,in = ParameterIn.HEADER),
@Parameter(name = "name",description = "文件名称",required = true,in=ParameterIn.QUERY)
})
@PostMapping("/bodyParamHeaderPath/{id}")
public ResponseEntity<FileResp> bodyParamHeaderPath(@PathVariable("id") String id,@RequestHeader("token") String token, @RequestParam("name")String name,@RequestBody FileResp fileResp){
fileResp.setName(fileResp.getName()+",receiveName:"+name+",token:"+token+",pathID:"+id);
return ResponseEntity.ok(fileResp);
}
}
4.最后访问Knife4j的文档
地址:http://ip:port/doc.html即可查看文档
注意的是:如果在配置文件中修改context-path信息,比如context-path: /imageanalyse,
那访问地址就是http://ip:port//imageanalyse/doc.html
也可以建立一个默认基础Controller,当请求路径是/或者/swagger时,路由默认调转到相对应的页面上
@RestController
@Tag(name = "默认基础Controller")
public class IndexController {
@Value("${server.servlet.context-path:#{null}}")
private String contextPath;
/**
* 自动跳转Knife4j-UI地址
*
* @param response
* @throws IOException
*/
@Operation(summary = "默认页跳转knife4j-ui")
@GetMapping("/")
public void index(HttpServletResponse response) throws IOException {
String redirectPath="/doc.html";
if(contextPath !=null && contextPath.length()>0){
redirectPath = contextPath+redirectPath;
}
response.sendRedirect(redirectPath);
}
/**
* 自动跳转Swagger-UI地址
*
* @param response
* @throws IOException
*/
@Operation(summary = "默认页跳转swagger-ui")
@GetMapping("/swagger")
public void swagger(HttpServletResponse response) throws IOException {
String redirectPath="/swagger-ui/index.html";
if(contextPath !=null && contextPath.length()>0){
redirectPath = contextPath+redirectPath;
}
response.sendRedirect(redirectPath);
}
}
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。
