SpringBoot集成Knife4f:最好用的Swagger接口文档和接口测试工具
一、kinfe4j介绍
GitHub:https://github.com/xiaoymin/swagger-bootstrap-ui
knife,简单翻译为小刀、匕首,从字面含义结合自身技术特性来说,确实实至名归,真正做到了小巧、轻量,并且功能强大,完美契合初中级程序员百分之八十的工作:增删改查(狗头)。
Knife4j一个是为了解决原始swagger-bootstrap-ui页面不美观,并且集成Swagger生成API文档而且可以在线测试接口的一种增强方案。
实现功能:
- 随项目启动生成接口文档,浏览器访问 ip:port/doc.html 即可访问,方便快捷;
- 接口统计
- 设置全局参数,设置后访问所有接口即可生效,例如请求头(Header)或者请求IP+port等;
- 下载离线接口文档:文档格式可以选择md、html、word、OpenAPI,当公司要求提供接口文档时,可以下载后导入ShowDoc等平台;
- 缓存功能:请求参数缓存;
- 接口过滤:可以选择只显示Post、Get等接口;
- 根据接口地址分组显示接口文档(接下来在代码中将实现)
- 测试接口
- 接口搜索
二、SpringBoot2.x集成
SpringBoot3.x版本暂无接触,以后可能会实现!
1. 添加依赖
<!-- https://mvnrepository.com/artifact/com.github.xiaoymin/knife4j-spring-boot-starter -->
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>knife4j-spring-boot-starter</artifactId>
<version>3.0.3</version>
</dependency>
2. 添加配置类
2.1 简单实现
@Configuration
@EnableSwagger2
public class SwaggerConfiguration {
@Bean
public Docket createDocApi() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.any())
.paths(PathSelectors.any())
.build()
.groupName("接口文档")
.pathMapping("/")
.apiInfo(DocApi());
}
/**
* 构建 api文档的详细信息函数,注意这里的注解引用的是哪个
*/
private ApiInfo DocApi() {
return new ApiInfoBuilder()
//页面标题
.title("接口测试工具")
//创建人
.contact(new Contact("", "", ""))
//版本号
.version("1.0")
//描述
.description("接口测试工具")
.build();
}
}
2.2 根据接口地址分组(正则实现)
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.EnableSwagger2;
@Configuration
@EnableSwagger2
public class SwaggerConfiguration {
private static final String USER_API_DOC = ".*(\\/api/user\\/).*";
private static final String BACK_API_DOC = ".*(\\/api/admin\\/).*";
/**
* 接口地址中包含/api/user
*/
@Bean
public Docket createUserApi() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.any())
.paths(PathSelectors.regex(USER_API_DOC))
.build()
.groupName("用户端接口文档")
.pathMapping("/")
.apiInfo(new ApiInfoBuilder()
//页面标题
.title("用户端接口文档")
//创建人
.contact(new Contact("", "", ""))
//版本号
.version("2.0")
//描述
.description("用户端接口文档")
.build()
);
}
/**
* 接口地址中包含/api/admin
*/
@Bean
public Docket createBackEndApi() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.any())
.paths(PathSelectors.regex(BACK_API_DOC))
.build()
.groupName("管理端接口文档")
.pathMapping("/")
.apiInfo(new ApiInfoBuilder()
//页面标题
.title("管理端接口文档")
//创建人
.contact(new Contact("", "", ""))
//版本号
.version("2.0")
//描述
.description("管理端接口文档")
.build()
);
}
}
3. 接口控制器注解
import com.github.xiaoymin.knife4j.annotations.ApiSupport;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
@RestController
@RequestMapping("/api/admin/coupon")
//接口文档一级标题
@Api(tags = "优惠券管理")
//接口作者,配置文件中 启动增强 才会生效
@ApiSupport(author = "张三")
public class CouponController {
@Resource
private WebCouponService webCouponService;
@GetMapping("/page")
//接口文档二级标题:真实接口
@ApiOperation(value = "查询分页列表", notes = "")
public ResultEntity<IPage<CouponPageResponse>> page(CouponPageRequest request) {
return ResultEntity.success(webCouponService.pageService(request));
}
}
4. 启动增强配置
knife4j:
# 增强功能开启
enable: true
# 开启生产环境屏蔽(该选项配置后,无法访问页面)
production: false
# 开启Swagger的Basic认证功能,默认是false,配置后登录才可访问页面
basic:
enable: true
# Basic认证用户名
username: admin
# Basic认证密码
password: 123456
5. 启动类增加快捷访问地址
@Slf4j
@SpringBootApplication
public class TestApplication {
public static void main(String[] args) {
SpringApplication app = new SpringApplication(TestApplication.class);
Environment env = app.run(args).getEnvironment();
app.setBannerMode(Banner.Mode.CONSOLE);
logApplicationStartup(env);
}
private static void logApplicationStartup(Environment env) {
String protocol = "http";
if (env.getProperty("server.ssl.key-store") != null) {
protocol = "https";
}
String serverPort = env.getProperty("server.port");
String contextPath = env.getProperty("server.servlet.context-path");
if (StringUtils.isBlank(contextPath)) {
contextPath = "/doc.html";
} else {
contextPath = contextPath + "/doc.html";
}
String hostAddress = "localhost";
try {
hostAddress = InetAddress.getLocalHost().getHostAddress();
} catch (UnknownHostException e) {
log.warn("The host name could not be determined, using `localhost` as fallback");
}
log.info("\n----------------------------------------------------------\n\t" +
"Application '{}' is running! Access URLs:\n\t" +
"Local: \t\t{}://localhost:{}{}\n\t" +
"External: \t{}://{}:{}{}\n\t" +
"Profile(s): \t{}\n----------------------------------------------------------",
env.getProperty("spring.application.name"),
protocol,
serverPort,
contextPath,
protocol,
hostAddress,
serverPort,
contextPath,
env.getActiveProfiles());
}
}
效果图
这样点击后直接跳到浏览器,不用再从浏览器输入地址。
三、常见问题及解决方法
1. 项目启动报错:Failed to read candidate component class: URL [jar:file:/C:/Users/xxx/.m2/repository/io/springfox/springfox-spring-webmv…
如图:
解决方法:引入springfox依赖
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-boot-starter</artifactId>
<version>3.0.0</version>
</dependency>
2. 访问doc.html控制台报错:java.lang.NumberFormatException: For input string: "”
如图:
虽然不影响正常使用,但是看着别扭,解决方法如下:
springfox中,去除swagger-annotations
和swagger-models
,并且重新引入1.5.21版本
代码如下:
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-boot-starter</artifactId>
<version>3.0.0</version>
<exclusions>
<exclusion>
<groupId>io.swagger</groupId>
<artifactId>swagger-annotations</artifactId>
</exclusion>
<exclusion>
<groupId>io.swagger</groupId>
<artifactId>swagger-models</artifactId>
</exclusion>
<exclusion>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>io.swagger</groupId>
<artifactId>swagger-annotations</artifactId>
<version>1.5.21</version>
</dependency>
<dependency>
<groupId>io.swagger</groupId>
<artifactId>swagger-models</artifactId>
<version>1.5.21</version>
</dependency>
3. 访问doc.html报404或者Nginx502
解决方法:增加Spring MVC映射地址,配置类实现WebMvcConfigurer
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("doc.html").addResourceLocations("classpath:/META-INF/resources/");
registry.addResourceHandler("/favicon.ico").addResourceLocations("classpath:/META-INF/resources/");
registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
}
四、个人建议
在最近开发一个统计接口中,返回json数据中包含Bigdecimal的数据结构,整数的数据,直接把小数点和小数点后的零全部自动抹掉了,这个与实际的业务不符。
如图:
建议一些涉及到数字的接口,不要完全信任某个工具,可以再次用Postman测试一下,两个工具如果结果一样,才算接口返回正常,否则还需要再次修改。