knife4j配置以及注意

java / 2021-12-22

knife4j

使用之前必须要导包
使用2.0.9的 knife4j不能使用2.6.0以上版本的 springboot 所以在这一步必须做一个降级处理

如果使用的是 2.6.0以上的springboot版本就会发生如下错误

Failed to start bean 'documentationPluginsBootstrapper'; nested exception is java.lang.NullPointerException
pom
  <properties>
        <java.version>11</java.version>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <spring-boot.version>2.5.8</spring-boot.version>
  </properties>


    <dependencies>
        <!--   knife4j在线文档     -->
        <dependency>
            <groupId>com.github.xiaoymin</groupId>
            <artifactId>knife4j-spring-boot-starter</artifactId>
            <version>2.0.9</version>
        </dependency>
	   </dependencies>

配置类

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.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2WebMvc;

@Configuration
@EnableSwagger2WebMvc
public class Knife4jConfiguration {


    @Bean(value = "defaultApi2")
    public Docket defaultApi2() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(new ApiInfoBuilder()
                        .contact(new Contact("zwy","http://120.24.28.124","xiaoyang@heypad.cn"))
                        //.title("swagger-bootstrap-ui-demo RESTful APIs")
                        .description("个人学习网站")
                        .termsOfServiceUrl("http://120.24.28.124")
                        .version("1.0")
                        .build())
                //分组名称
                .groupName("1.0.0版本")
                .select()
                //这里指定Controller扫描包路径
                .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
                .paths(PathSelectors.any())
                .build()
                .securitySchemes(securitySchemes());
    }

    /**
     * 安全模式,这里配置通过请求头 openid传递 openid 参数
     */
    private static List<SecurityScheme> securitySchemes() {
        return Collections.singletonList(new ApiKey("openid", "openid", "header"));
    }

}