Springboot集合SwaggerV3(OpenAPI)+ Knife4J 生成接口文档

SwaggerV3(OpenAPI)+ Knife4J

  • SwaggerV3是一种规范,可以描述RESTful
    API,它提供了一种标准格式,方便框架和工具之间进行统一;而Knife4J则是基于SwaggerV3规范的一个前端UI实现,它可以更好地展示Swagger规范生成的文档,包括展示样式和功能配置等。

  • 使用SpringBoot集成SwaggerV3和Knife4J,可以让开发人员通过注解等方式快速地配置API接口的相关信息,如参数、返回值、描述等,同时自动生成相应的API文档,并提供在线测试API的功能。这能够大大提升项目的开发效率和质量,同时也方便了维护和管理工作。

  • Knife4J是一款基于Swagger快速生成API文档和调试平台的开源工具,它可以轻松地将Swagger规范转换成易于阅读的文档,并支持在线测试API。Knife4J内置了多种主题和插件,提供了丰富的样式和功能配置,可以自定义API文档的展示方式和内容。同时,Knife4J还支持在线调试API接口,可以通过web界面直接调用接口,参数和返回值都会进行实时展示,让开发人员快速测试和调试API接口。

接下来我们来使用Springboot集合SwaggerV3(OpenAPI)+ Knife4J 生成接口文档

POM

首先添加maven依赖如下

    
        com.github.xiaoymin
        knife4j-spring-boot-starter
        3.0.3
    

yml配置

在application.yml配置文件中添加以下信息

knife4j:
    enable: true
    documents:
      - group: Test Group
        name: My Documents
        locations: classpath:wiki/\*
    setting:
      # default lang
      language: en-US
      # footer
      enableFooter: false
      enableFooterCustom: true
      # header
      enableHomeCustom: true
      homeCustomLocation: classpath:wiki/README.md
      # models
      enableSwaggerModels: true
      swaggerModelName: My Models

注入配置

使用@Configuration注入一个Knife4jConfiguration类并使用@EnableKnife4j 使Knife4j 生效,该注解是为了解决springboot与Knife4j版本冲突可能导致无法运行的问题。
使用@Bean注入webMvcEndpointHandlerMapping是为了解决springboot-admin等与Knife4J的冲突问题

import com.github.xiaoymin.knife4j.spring.annotations.EnableKnife4j;
import org.springframework.boot.actuate.autoconfigure.endpoint.web.CorsEndpointProperties;
import org.springframework.boot.actuate.autoconfigure.endpoint.web.WebEndpointProperties;
import org.springframework.boot.actuate.autoconfigure.web.server.ManagementPortType;
import org.springframework.boot.actuate.endpoint.ExposableEndpoint;
import org.springframework.boot.actuate.endpoint.web.*;
import org.springframework.boot.actuate.endpoint.web.annotation.ControllerEndpointsSupplier;
import org.springframework.boot.actuate.endpoint.web.annotation.ServletEndpointsSupplier;
import org.springframework.boot.actuate.endpoint.web.servlet.WebMvcEndpointHandlerMapping;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
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 java.util.ArrayList;
import java.util.Collection;
import java.util.List;

@Configuration
@EnableKnife4j
public class Knife4jConfiguration implements WebMvcConfigurer {

    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                //将basePackage中换为你自己项目所在的位置,如com.example.*
                .apis(RequestHandlerSelectors.basePackage("tech.mybatis.plus.springboot.study.details"))
                .paths(PathSelectors.any())
                .build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("My API Documentation")
                .version("1.0")
                .description("My API documentation powered by Knife4j")
                .termsOfServiceUrl("https://example.com/terms")
                .license("Apache License 2.0")
                .licenseUrl("https://www.apache.org/licenses/LICENSE-2.0.html")
                .build();
    }
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/**")
                .addResourceLocations("classpath:/static/");
        registry.addResourceHandler("doc.html")
                .addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("/webjars/**")
                .addResourceLocations("classpath:/META-INF/resources/webjars/");
    }
    //这里是为了解决springboot-admin等与Knife4J的冲突问题
    @Bean
    public WebMvcEndpointHandlerMapping webMvcEndpointHandlerMapping(WebEndpointsSupplier webEndpointsSupplier, ServletEndpointsSupplier servletEndpointsSupplier,
                                                                     ControllerEndpointsSupplier controllerEndpointsSupplier, EndpointMediaTypes endpointMediaTypes, CorsEndpointProperties corsEndpointProperties, WebEndpointProperties webEndpointProperties,
                                                                     Environment environment) {
        List<ExposableEndpoint<?>> allEndpoints = new ArrayList<>();
        Collection<ExposableWebEndpoint> webEndpoints = webEndpointsSupplier.getEndpoints();
        allEndpoints.addAll(webEndpoints);
        allEndpoints.addAll(servletEndpointsSupplier.getEndpoints());
        allEndpoints.addAll(controllerEndpointsSupplier.getEndpoints());
        String basePath = webEndpointProperties.getBasePath();
        EndpointMapping endpointMapping = new EndpointMapping(basePath);
        boolean shouldRegisterLinksMapping = shouldRegisterLinksMapping(webEndpointProperties, environment, basePath);
        return new WebMvcEndpointHandlerMapping(endpointMapping, webEndpoints, endpointMediaTypes, corsEndpointProperties.toCorsConfiguration(), new EndpointLinksResolver(
                allEndpoints, basePath), shouldRegisterLinksMapping, null);
    }

    private boolean shouldRegisterLinksMapping(WebEndpointProperties webEndpointProperties, Environment environment, String basePath) {
        return webEndpointProperties.getDiscovery().isEnabled() && (StringUtils.hasText(basePath) || ManagementPortType.get(environment).equals(ManagementPortType.DIFFERENT));
    }
}

Controller接口

在controller接口中添加@Api(value = “value”, tags = “tags”) 即表示为这个接口生成接口文档

@Api(value = "User Interfaces", tags = "User Interfaces")
@Controller
@RequestMapping("/details/tbUser")
public class TbUserController {
 @Autowired
    private ITbUserService iTbUserService;
 @PostMapping("add")
    @ResponseBody
    public ResponseEntity<?> add(@Valid @RequestBody TbUserParam tbuserParam) {
           return iTbUserService.addUser(tbuserParam);
    }


    @GetMapping("selectById/{userId}")
    @ResponseBody
    public ResponseResult<TbUser> selectById(@PathVariable("userId") String userId) {
        return iTbUserService.selectById(userId);
    }
}

运行测试

默认为 localhost:8080/doc.html
如果运行失败,则可能是springboot版本不兼容,在yml中添加以下配置即可:

spring:
   mvc:
    path match:
      matching-strategy: ant_path_matcher

你可能感兴趣的:(springboot相关,spring,boot,java,spring,测试工具,后端)