1. SpringBoor整合Knife4j添加maven
1.1 第一种maven
<!--添加Knife4j依赖-->
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>knife4j-openapi3-jakarta-spring-boot-starter</artifactId>
<version>4.5.0</version>
</dependency>
1.2 第2种maven (我用第二种)
<!-- knife4j-maven -->
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>knife4j-spring-boot-starter</artifactId>
<version>3.0.3</version>
</dependency>
2. 修改yml文件
# springdoc-openapi项目配置
springdoc:
swagger-ui:
path: /swagger-ui.html
# 排序方式为首字母
tags-sorter: alpha
# 使用增强order属性进行排序,或者不设置该参数( @ApiOperationSupport(order = n)直接生效)
operations-sorter: order
api-docs:
path: /v3/api-docs
group-configs:
#组名可以自己设置
- group: 'default'
paths-to-match: '/**'
# controller所在包
packages-to-scan: com.knifej.test.controller
# knife4j的增强配置,不需要增强可以不配
knife4j:
enable: true
setting:
language: zh_cn
3. 创建Knife4J配置类
配置类Knife4jConfig,为了避免导错包,把包也给了
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
@Configuration
@EnableSwagger2
public class Knife4jConfig {
@Bean(value = "defaultApi2")
public Docket defaultApi2() {
Docket docket = new Docket(DocumentationType.SWAGGER_2)
.apiInfo(new ApiInfoBuilder()
.title("xxx接口说明")
.description("xxx接口描述")
.termsOfServiceUrl("http://www.xx.com/")
.contact(new Contact("xxx公司", "http://xxx.com/", "xxx@xxx.com"))
.version("1.0")
.build())
//分组名称
.groupName("2.X版本")
.select()
//这里指定Controller扫描包路径
.apis(RequestHandlerSelectors.basePackage("com.xxx.controller"))
.paths(PathSelectors.any())
.build();
return docket;
}
}
4. 控制层Controller
package com.eric.springbootknife4j.admin;
import com.eric.springbootknife4j.entity.SwaggerUser;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.ArrayList;
import java.util.List;
/**
* @author Eric
* @date 2023-07-31 9:50
*/
@Api(tags = "用户端控制器")
@RestController
@RequestMapping("/admin")
public class AdminController {
@ApiOperation(value = "获取数据")
@GetMapping("/test")
public List<SwaggerUser> test(@ApiParam(name = "id",value = "用户Id") Long id,
@ApiParam(name = "name",value = "用户名称") String name){
List<SwaggerUser> list = new ArrayList<>();
list.add(SwaggerUser.builder().id(id).name(name).build());
return list;
}
}