springboot 项目集成 knife4j
要在Spring Boot项目中集成Knife4j,你需要按照以下步骤操作:
- 在
pom.xml
中添加Knife4j的依赖。
<dependencies>
<!-- 添加swagger2依赖 -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
<!-- 添加swagger-ui依赖 -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
<!-- 添加knife4j依赖 -->
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>knife4j-spring-boot-starter</artifactId>
<version>2.0.9</version>
</dependency>
</dependencies>
- 配置Swagger2。
创建一个配置类,如SwaggerConfig
,使用@Configuration
注解标注这是一个配置类,并使用@EnableSwagger2
开启Swagger2。
import com.github.xiaoymin.knife4j.spring.annotations.EnableKnife4j;
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.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
@Configuration
@EnableSwagger2
@EnableKnife4j
public class SwaggerConfig {
@Bean(value = "defaultApi2")
public Docket defaultApi2() {
Docket docket=new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
// 指定扫描的包路径
.apis(RequestHandlerSelectors.basePackage("com.example.demo.controller"))
.paths(PathSelectors.any())
.build();
return docket;
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("Knife4j Demo")
.description("Knife4j的接口文档")
.version("1.0")
.build();
}
}
- 在
application.properties
或application.yml
中配置(可选)。
# application.properties
# 可以配置swagger的访问路径
#springfox.documentation.swagger.v2.path=/api-docs
- 创建Controller并使用Swagger注解。
import io.swagger.annotations.Api;
import io.swagger.annotations
评论已关闭