SpringBoot集成Knife4j:最好用的Swagger接口文档和接口测试工具

SpringBoot集成Knife4f:最好用的Swagger接口文档和接口测试工具

一、kinfe4j介绍

官网:https://doc.xiaominfo.com/

GitHub:https://github.com/xiaoymin/swagger-bootstrap-ui

knife,简单翻译为小刀、匕首,从字面含义结合自身技术特性来说,确实实至名归,真正做到了小巧、轻量,并且功能强大,完美契合初中级程序员百分之八十的工作:增删改查(狗头)。

Knife4j一个是为了解决原始swagger-bootstrap-ui页面不美观,并且集成Swagger生成API文档而且可以在线测试接口的一种增强方案。

实现功能

  1. 随项目启动生成接口文档,浏览器访问 ip:port/doc.html 即可访问,方便快捷;
  2. 接口统计
    在这里插入图片描述
  3. 设置全局参数,设置后访问所有接口即可生效,例如请求头(Header)或者请求IP+port等;
    在这里插入图片描述
  4. 下载离线接口文档:文档格式可以选择md、html、word、OpenAPI,当公司要求提供接口文档时,可以下载后导入ShowDoc等平台;
    在这里插入图片描述
  5. 缓存功能:请求参数缓存;
  6. 接口过滤:可以选择只显示Post、Get等接口;
    在这里插入图片描述
  7. 根据接口地址分组显示接口文档(接下来在代码中将实现)
    在这里插入图片描述
  8. 测试接口
    在这里插入图片描述
  9. 接口搜索
    在这里插入图片描述

二、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-annotationsswagger-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测试一下,两个工具如果结果一样,才算接口返回正常,否则还需要再次修改。

  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: Knife4j 是一个基于 SwaggerAPI 开发工具,可以帮助开发者快速构建和管理 RESTful API。要集成 Knife4jSpringBoot 项目中,可以参考以下步骤: 1. 在 pom.xml 文件中添加 Knife4j 依赖; 2. 配置 Knife4j 的扫描路径; 3. 配置 Knife4j 的 UI 配置; 4. 配置 Knife4j 的全局配置; 5. 启动 SpringBoot 项目,访问 Knife4j UI。 ### 回答2: 要将Knife4j集成Spring Boot项目中,需要进行以下步骤: 第一步是在项目的pom.xml文件中添加Knife4j的依赖项。可以通过在dependencies标签内添加以下代码来实现: ``` <dependency> <groupId>com.github.xiaoymin</groupId> <artifactId>knife4j-spring-boot-starter</artifactId> <version>2.0.8</version> </dependency> ``` 第二步是在Spring Boot的配置类中添加@EnableSwagger2Doc注解来启用Knife4j: ``` @Configuration @EnableSwagger2Doc public class SwaggerConfig { // 可以在这里进行一些其他的Swagger配置 } ``` 第三步是配置Swagger的基本信息,例如标题、描述等。在application.properties文件中添加以下配置: ``` knife4j.title=API接口文档 knife4j.description=这是一个使用Knife4j生成的接口文档 knife4j.version=1.0 ``` 第四步是在项目启动后,访问http://localhost:8080/doc.html(假设项目运行在localhost的8080端口)来查看Knife4j生成的接口文档页面。 集成完成后,可以在项目中使用一些注解来对接口进行描述、分组、授权等操作。例如,可以使用@Api注解来描述一个接口的基本信息,使用@ApiOperation注解来描述接口的操作等。 以上是将Knife4j集成Spring Boot项目中的基本步骤。集成成功后,可以方便地生成和查看项目的接口文档,提高了API的可维护性和可读性。 ### 回答3: Spring Boot是一个开源的Java框架,可以用于快速构建基于Spring的应用程序。Knife4j是一个基于SwaggerAPI接口文档生成工具,可以方便地生成接口文档。 要集成Knife4jSpring Boot项目中,首先需要在项目的pom.xml文件中添加Knife4j的依赖项。可以通过以下代码将其添加到pom.xml文件中: ``` <dependency> <groupId>com.github.xiaoymin</groupId> <artifactId>knife4j-spring-boot-starter</artifactId> <version>2.0.6</version> </dependency> ``` 添加完依赖项后,需要在项目的配置文件(application.properties或application.yml)中配置Knife4j相关的属性。例如,可以添加以下配置来设置文档页面的标题和描述: ``` knife4j.title=API接口文档 knife4j.description=这是一个演示项目的API接口文档 ``` 配置好属性后,可以在项目的启动类上添加`@EnableKnife4j`注解来启用Knife4j: ```java @SpringBootApplication @EnableKnife4j public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } } ``` 启动项目后,访问`http://localhost:8080/doc.html`即可看到生成的接口文档页面。在这个页面上,可以查看项目中定义的API接口,并且可以方便地进行测试。 总的来说,集成Knife4jSpring Boot项目中很简单,只需要添加依赖、配置属性,然后在启动类上添加注解即可。通过Knife4j生成的接口文档可以方便地查看和测试API接口,使得开发过程更加高效。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值