1、添加依赖
在pom.xml 文件中添加 knife4j-spring-boot-starter 的依赖
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>knife4j-spring-boot-starter</artifactId>
<version>3.0.3</version>
</dependency>
2、配置
# application.yml
knife4j:
enable: true # 开启Knife4j增强功能
base-package: com.xxx.xxx.controller # 设置需要扫描的包路径
3、使用Swagger注解
为实体类添加@ApiModel注解和ApiModelProperty注解
例如:
@ApiModel("用户实体类")
@Data
@TableName("employee")
public class Employee implements Serializable {
@ApiModelProperty("用户Id")
@TableField(value = "id", select = false)
@TableId(type = IdType.ASSIGN_ID)
private Long id;
@ApiModelProperty("用户名称")
private String name;
@ApiModelProperty("用户密码")
private String password;
@TableField(value = "create_time",fill = FieldFill.INSERT)
@JsonFormat(pattern="yyyy-MM-dd HH:mm:ss",timezone="GMT+8")
private LocalDateTime createTime;
@TableField(value = "update_time",fill = FieldFill.INSERT_UPDATE)
@JsonFormat(pattern="yyyy-MM-dd HH:mm:ss",timezone="GMT+8")
private LocalDateTime updateTime;
}
在 Controller 类和方法上使用 Swagger 的注解来描述 API
@Api(tags = "示例接口")
@RestController
@RequestMapping("/example")
public class ExampleController {
@ApiOperation("获取示例数据")
@GetMapping("/data")
public String getData() {
return "示例数据";
}
}
4、定义API文档的标题、描述、版本等信息
创建配置类 SwaggerConfig :
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
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
public class SwaggerConfig {
@Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.any())
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfo(
"你的API标题", // title
"你的API描述", // description
"1.0", // version
"Terms of service", // termsOfServiceUrl
"你的联系人名字", // contact
"你的API许可证", // license
"你的API许可证URL" // licenseUrl
);
}
}
5、启动并访问
启用springboot项目,在浏览器访问项目的/doc.html
路径