SpringBoot整合Knife4j(Swagger升级版)实现

Knife4j简介

knife4j是为Java MVC框架集成Swagger生成Api文档的增强解决方案。
all
图中展示了某一个Get请求的详情页面,
右上方可进行接口搜索,快速查找到对应接口;
左侧接口树状展示,右侧详情展示,更加清晰;
调试会自动匹配参数;
response json可折叠展示;
······众多优点

pom.xml

想要在项目中应用Knife4j,首先需要导入相关依赖如下:

    <!--整合Knife4j-->
    <dependency>
        <groupId>com.github.xiaoymin</groupId>
        <artifactId>knife4j-spring-boot-starter</artifactId>
        <version>2.0.6</version>
    </dependency>

SwaggerConfig.java

Knife4j生效,需要配合注解**@EnableKnife4j**使用。如下代码所示加在类上。

import com.github.xiaoymin.knife4j.spring.annotations.EnableKnife4j;
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.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@Configuration
@EnableSwagger2
@EnableKnife4j
public class SwaggerConfig {

    @Bean
    public Docket api() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .host("localhost:***/")
                .select()
                .apis(RequestHandlerSelectors.basePackage("******"))
                .paths(PathSelectors.any())
                .build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("******")
                .description("******")
                .version("1.0")
                .build();
    }
}

WebMvcConfigurationSupport

如果项目使用了WebMvcConfigurationSupport进行增强,需要在对应类–addResourceHandlers() 方法中加入如下代码

registry.addResourceHandler("doc.html").addResourceLocations("classpath:/META-INF/resources/");

启动测试

访问http://localhost:端口号/doc.html
成功运行起来了!!

success

官方文档

https://doc.xiaominfo.com


版权声明:本文为weixin_45812467原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。