是什么
Knife4j
是一个集Swagger2
和OpenAPI3
为一体的增强解决方案
添加依赖
<!--引入Knife4j的官方start包,该指南选择Spring Boot版本<3.0,开发者需要注意-->
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>knife4j-openapi2-spring-boot-starter</artifactId>
<version>4.0.0</version>
</dependency>
创建配置类
package com.example.demospringbootdemo.config;
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.EnableSwagger2WebMvc;
@Configuration
@EnableSwagger2WebMvc
public class Knife4jConfiguration {
@Bean(value = "dockerBean")
public Docket dockerBean() {
//指定使用Swagger2规范
Docket docket=new Docket(DocumentationType.SWAGGER_2)
.apiInfo(new ApiInfoBuilder()
//描述字段支持Markdown语法
.description("# Knife4j RESTful APIs")
.termsOfServiceUrl("https://itl-coder.github.io/")
.contact("ituninapp@gmail.com")
.version("1.0")
.build())
//分组名称
.groupName("用户服务")
.select()
//这里指定Controller扫描包路径
.apis(RequestHandlerSelectors.basePackage("com.example.demospringbootdemo.controller"))
.paths(PathSelectors.any())
.build();
return docket;
}
}
控制器的使用
实体类参数
@RestController
@Api(tags = "用户管理", description = "提供用户信息的接口")
public class UserController {
@ApiOperation(value = "对接口功能的说明", notes = "根据用户传入的信息返回用户对象")
@GetMapping("/user")
public User sayUser(User user) {
return user;
}
}
普通字段
package com.example.demospringbootdemo.controller;
import com.example.demospringbootdemo.domain.User;
import io.swagger.annotations.*;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@Api(tags = "用户管理", description = "提供用户信息的接口")
public class UserController {
@ApiOperation(value = "对接口功能的说明")
@GetMapping("/hello")
public String sayHello(
@ApiParam(name = "username", required = false, defaultValue = "coder-itl") String username,
@ApiParam(name = "password", required = true, defaultValue = "123") String password) {
return username + " " + password;
}
}
实体类使用
@Data
@NoArgsConstructor
@AllArgsConstructor
@ApiModel(value = "用户实体")
public class User {
@ApiModelProperty(value="姓名",example="张飞")
private String username;
@ApiModelProperty(value="密码",example="123",required = true)
private Integer password;
}
启动
http://localhost:8080/doc.html