Knife4j官方文档:快速开始 | Knife4j
1.引入依赖,注意版本兼容(可在官方文档查看对应版本兼容)
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>knife4j-spring-boot-starter</artifactId>
<version>3.0.3</version>
</dependency>
2.编写Knife4jConfig 配置类
@Configuration
@EnableSwagger2//启用了Swagger 2的支持
@Profile({"dev", "test"})//注解指定了这个配置类只有在特定的Spring profiles(dev 和 test)激活时才会被加载。这意味着在生产环境中(通常profile为prod),这个配置不会生效
public class Knife4jConfig {
@Bean
public Docket defaultApi2() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(new ApiInfoBuilder()
.title("接口文档")
.description("yubi-backend")
.version("1.0")
.build())
.select()
// 指定 Controller 扫描包路径
.apis(RequestHandlerSelectors.basePackage("controller的路径"))
.paths(PathSelectors.any())
.build();
}
}
3.如果 springboot version >= 2.6,需要添加如下配置
spring:
mvc:
pathmatch:
matching-strategy: ant_path_matcher
4.启动项目,输入地址(根据自己项目的ip和port)
http://ip:port/doc.html
如果配置了/api
server:
address: 0.0.0.0
port: 8080
servlet:
#以 /api 作为请求路径的前缀
context-path: /api
,则地址需要改为
http://ip:port/api/doc.html