说明
knife4j是为Java MVC框架集成Swagger生成Api文档的增强解决方案,前身是swagger-bootstrap-ui,取名kni4j是希望它能像一把匕首一样小巧,轻量,并且功能强悍!。
功能
- 文档说明:根据Swagger的规范说明,详细列出接口文档的说明,包括接口地址、类型、请求示例、请求参数、响应示例、响应参数、响应码等信息,使用swagger-bootstrap-ui能根据该文档说明,对该接口的使用情况一目了然。
- 在线调试:提供在线接口联调的强大功能,自动解析当前接口参数,同时包含表单验证,调用参数可返回接口响应内容、headers、Curl请求命令实例、响应时间、响应状态码等信息,帮助开发者在线调试,而不必通过其他测试工具测试接口是否正确,简介、强大。
完整代码地址在结尾!!
第一步,在pom.xml加入依赖,如下
<!-- knife4j -->
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>knife4j-spring-boot-starter</artifactId>
<version>2.0.2</version>
</dependency>
第二步,配置application.yml,避免端口冲突
server:
port: 8081
第三步,创建类TestRequest,TestResponse,如下
TestRequest
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
/**
* @Description:
* @Author: luoyu
* @Date: 2020/5/14 9:30 下午
* @Version: 1.0.0
*/
@Data
public class TestRequest {
@ApiModelProperty(required = true, value = "用户id", example = "123")
private String id;
@ApiModelProperty(required = true, value = "用户name", example = "百里玄刺")
private String name;
@ApiModelProperty(required = true, value = "用户age", example = "18")
private int age;
@ApiModelProperty(required = true, value = "用户sex", example = "男")
private String sex;
}
TestResponse
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
/**
* @Description:
* @Author: luoyu
* @Date: 2020/5/14 9:30 下午
* @Version: 1.0.0
*/
@ApiModel("getTest响应实体")
@Data
public class TestResponse {
@ApiModelProperty(required = true, value = "用户id", example = "123")
private String id;
@ApiModelProperty(required = true, value = "用户name", example = "百里玄刺")
private String name;
@ApiModelProperty(required = true, value = "用户age", example = "18")
private int age;
@ApiModelProperty(required = true, value = "用户sex", example = "男")
private String sex;
}
第四步,创建类Test1Controller,Test2Controller,Test3Controller(在接口上添加对应注解,本人只添加基本的注解),并分别放于com.luoyu.knife4j.controller.test1,com.luoyu.knife4j.controller.test2,com.luoyu.knife4j.controller.test3包下(配置文件里面配置的扫描路径)。
Test1Controller
import com.luoyu.knife4j.entity.request.TestRequest;
import com.luoyu.knife4j.entity.response.TestResponse;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* <p>
* 前端控制器
* </p>
*
* @author luoyu
* @since 2020-02-13
*/
@RestController
@RequestMapping("/test1")
@Api(value = "/test1", tags = "Test1Controller接口")
public class Test1Controller {
/**
* @author luoyu
* @description 测试接口1
*/
@ApiResponses({
@ApiResponse(code = 200, message = "成功!"),
@ApiResponse(code = 500, message = "服务器内部错误,请联系管理人员!"),
@ApiResponse(code=404,message="请求路径没有或页面跳转路径不对")
})
@PostMapping(value = "/gettest1", produces = "application/json; charset=UTF-8")
@ApiOperation(value = "test1接口名称", notes = "test1接口描述")
public TestResponse getTest1(TestRequest request) throws Exception {
TestResponse response = new TestResponse();
BeanUtils.copyProperties(request, response);
return response;
}
/**
* @author luoyu
* @description 测试接口2
*/
@ApiResponses({
@ApiResponse(code = 200, message = "成功!"),
@ApiResponse(code = 500, message = "服务器内部错误,请联系管理人员!"),
@ApiResponse(code=404,message="请求路径没有或页面跳转路径不对")
})
@PostMapping(value = "/gettest2", produces = "application/json; charset=UTF-8")
@ApiOperation(value = "test2接口名称", notes = "test2接口描述")
public TestResponse getTest2(TestRequest request) throws Exception {
TestResponse response = new TestResponse();
BeanUtils.copyProperties(request, response);
return response;
}
}
Test2Controller
import com.luoyu.knife4j.entity.request.TestRequest;
import com.luoyu.knife4j.entity.response.TestResponse;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* <p>
* 前端控制器
* </p>
*
* @author luoyu
* @since 2020-02-13
*/
@RestController
@RequestMapping("/test2")
@Api(value = "/test2", tags = "Test2Controller接口")
public class Test2Controller {
/**
* @author luoyu
* @description 测试接口1
*/
@ApiResponses({
@ApiResponse(code = 200, message = "成功!"),
@ApiResponse(code = 500, message = "服务器内部错误,请联系管理人员!"),
@ApiResponse(code=404,message="请求路径没有或页面跳转路径不对")
})
@PostMapping(value = "/gettest1", produces = "application/json; charset=UTF-8")
@ApiOperation(value = "test1接口名称", notes = "test1接口描述")
public TestResponse getTest1(TestRequest request) throws Exception {
TestResponse response = new TestResponse();
BeanUtils.copyProperties(request, response);
return response;
}
}
Test3Controller
import com.luoyu.knife4j.entity.request.TestRequest;
import com.luoyu.knife4j.entity.response.TestResponse;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* <p>
* 前端控制器
* </p>
*
* @author luoyu
* @since 2020-02-13
*/
@RestController
@RequestMapping("/test3")
@Api(value = "/test3", tags = "Test3Controller接口")
public class Test3Controller {
/**
* @author luoyu
* @description 测试接口1
*/
@ApiResponses({
@ApiResponse(code = 200, message = "成功!"),
@ApiResponse(code = 500, message = "服务器内部错误,请联系管理人员!"),
@ApiResponse(code=404,message="请求路径没有或页面跳转路径不对")
})
@PostMapping(value = "/gettest1", produces = "application/json; charset=UTF-8")
@ApiOperation(value = "test1接口名称", notes = "test1接口描述")
public TestResponse getTest1(TestRequest request) throws Exception {
TestResponse response = new TestResponse();
BeanUtils.copyProperties(request, response);
return response;
}
}
第五步,创建Knife4jConfig配置文件,如下
import com.github.xiaoymin.knife4j.spring.annotations.EnableKnife4j;
import com.google.common.base.Function;
import com.google.common.base.Predicate;
import com.google.common.collect.Lists;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.Profile;
import springfox.bean.validators.configuration.BeanValidatorPluginsConfiguration;
import springfox.documentation.RequestHandler;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.ParameterBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.schema.ModelRef;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Parameter;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
/**
* @version 1.0
* @author luoyu
* @date 2019-08-09
* @description Knife4j配置
*/
@Configuration
@EnableSwagger2
@EnableKnife4j
@Import(BeanValidatorPluginsConfiguration.class)
public class Knife4jConfig {
/**
* 定义分隔符
*/
private static final String SPLITOR = ";";
/**
* @author luoyu
* @description 配置token,以及设置扫描包的路径
* @return Docket
*/
@Bean("createRestApi1")
public Docket createRestApi1() {
//设置header里面的token
ParameterBuilder tokenPar = new ParameterBuilder();
List<Parameter> pars = new ArrayList<>();
tokenPar.name("token").description("token令牌").modelRef(new ModelRef("string")).parameterType("header").required(false).build();
pars.add(tokenPar.build());
return new Docket(DocumentationType.SWAGGER_2)
.globalOperationParameters(pars)
.apiInfo(apiInfo())
.groupName("1.0.0 版本")
.select()
//此处添加需要扫描接口的包路径
.apis(basePackage("com.luoyu.knife4j.controller.test1" + SPLITOR
+ "com.luoyu.knife4j.controller.test2" + SPLITOR ))
.paths(PathSelectors.any())
.build();
}
/**
* @author luoyu
* @description 配置token,以及设置扫描包的路径
* @return Docket
*/
@Bean("createRestApi2")
public Docket createRestApi2() {
//设置header里面的token
ParameterBuilder tokenPar = new ParameterBuilder();
List<Parameter> pars = new ArrayList<>();
tokenPar.name("token").description("token").modelRef(new ModelRef("string")).parameterType("header").required(false).build();
pars.add(tokenPar.build());
return new Docket(DocumentationType.SWAGGER_2)
.globalOperationParameters(pars)
.apiInfo(apiInfo())
.groupName("2.0.0 版本")
.select()
//此处添加需要扫描接口的包路径
.apis(basePackage("com.luoyu.knife4j.controller.test3" + SPLITOR ))
.paths(PathSelectors.any())
.build();
}
/**
* @author luoyu
* @description 配置Knife4j页面显示内容
* @return Docket
*/
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("Knife4j 接口文档")
.description("Knife4j 接口文档")
.version("1.0.0")
.termsOfServiceUrl("http://localhost:8088/doc.html")
.contact("luoyu")
.build();
}
/**
* @author luoyu
* @description 重写basePackage方法,使能够实现多包访问
* @param basePackage 所有包路径
* @return Predicate<RequestHandler>
*/
public static Predicate<RequestHandler> basePackage(final String basePackage) {
return input -> declaringClass(input).map(handlerPackage(basePackage)::apply).orElse(true);
}
/**
* @author luoyu
* @description 重写basePackage方法,使能够实现多包访问
* @param basePackage 所有包路径
* @return Function<Class<?>, Boolean>
*/
private static Function<Class<?>, Boolean> handlerPackage(final String basePackage) {
return input -> {
// 循环判断匹配
for (String strPackage : basePackage.split(SPLITOR)) {
assert input != null;
boolean isMatch = input.getPackage().getName().startsWith(strPackage);
if (isMatch) {
return true;
}
}
return false;
};
}
/**
* @author luoyu
* @description 重写basePackage方法,使能够实现多包访问
* @param input
* @return Optional<? extends Class<?>>
*/
private static Optional<Class<?>> declaringClass(RequestHandler input) {
return Optional.ofNullable(input.declaringClass());
}
}
第六步,启动项目,访问:http://localhost:8089/doc.html,
- 端口号根据配置文件application.yml里面的端口号进行修改
- 需要输入安全认证账号密码,也是application.yml里面配置的
另外,此处提供一些常用注解。如下
@Api() 用于类;表示标识这个类是swagger的资源
tags–表示说明
value–也是说明,可以使用tags替代
@ApiOperation() 用于方法;表示一个http请求的操作
value用于方法描述
notes用于提示内容
@ApiParam() 用于方法,参数,字段说明;表示对参数的添加元数据(说明或是否必填等)
name–参数名
value–参数说明
required–是否必填
@ApiModel()用于类 ;表示对类进行说明,用于参数用实体类接收
value–表示对象名
@ApiModelProperty()用于方法,字段; 表示对model属性的说明或者数据操作更改
value–字段说明
name–重写属性名字
dataType–重写属性类型
required–是否必填
example–举例说明
hidden–隐藏
@ApiImplicitParam() 用于方法
表示单独的请求参数
@ApiImplicitParams() 用于方法,包含多个 @ApiImplicitParam
name–参数ming
value–参数说明
dataType–数据类型
paramType–参数类型
example–举例说明
@ApiIgnore
作用于方法上,使用这个注解swagger将忽略这个接口