SpringBoot3项目使用Knife4j时访问doc.html出现Knife4j文档请求异常且开发者工具网络面板中swagger-resources请求出现404的处理心得

1.在各个pom.xml中替换Knife4j的依赖版本,升级为4.0以上,如果找不到依赖可以在Maven配置中多添加几个镜像,或者使用汉化插件重启IDEA;

<dependency>
        <groupId>com.github.xiaoymin</groupId>
        <artifactId>knife4j-openapi3-jakarta-spring-boot-starter</artifactId>
        <version>${knife4j}</version>
</dependency>    

 2.(主要在实体类的DTO和VO类中)用Swagger3注解替换Swagger2注解,变化规则如下:

@Api(tags = “”) → @Tag(name = “”)
@ApiModel(value=“”, description=“”) → @Schema(name=“”, description=“”)
@ApiModelProperty(value = “”, required = true) → @Schema(name= “”, description = “”, required = true)
@ApiOperation(value = “”, notes = “”) → @Operation(summary = “”, description = “”)
@ApiParam → @Parameter
@ApiResponse(code = 404, message = “”) → @ApiResponse(responseCode = “404”, description = “”)

 3.(可选)修改配置类,将extends WebMvcConfigurationSupport改为implements WebMvcConfigurer,并将重写的方法属性由protected改为public,

修改后可不重写静态资源映射的addResourceHandlers方法,因为因为implements了WebMvcConfigurer接口之后可以自动映射静态资源;

4.原配置类中的

    @Bean
    public Docket docket() {
        ApiInfo apiInfo = new ApiInfoBuilder()
                .title("")
                .version("")
                .description("")
                .build();
        Docket docket = new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo)
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.sky.controller"))
                .paths(PathSelectors.any())
                .build();
        return docket;
    }

修改为

    @Bean
    public OpenAPI publicApi(Environment environment) {
        return new OpenAPI()
                //.servers(serverList())
                .info(new Info()
                        .title("")
                        //.extensions(Map.of("x-audience", "external-partner", "x-application-id", "APP-12345"))
                        .description("")
                        .version("")
                );
        //.addSecurityItem(new SecurityRequirement().addList("bearer-jwt", Arrays.asList("read", "write"))).security(securityList());
    }

5.大功告成,可成功访问swagger-ui以及doc.html,如果想将文档分组显示的话,需要在yml配置文件中自行设置:

springdoc:
  api-docs:
    path: /v3/api-docs
  packages-to-scan: 
  group-configs:
    - group: admin
      paths-to-match:
        - /admin/**
      packages-to-scan:
        - 
    - group: user
      paths-to-match:
        - /user/**
      packages-to-scan:
        - 

 

 参考链接:

抛弃 springfox,拥抱 springdoc - 知乎 (zhihu.com)

项目升级SpringBoot3:java.lang.ClassNotFoundException: javax.servlet.http.HttpServletRequest_java.lang.classnotfoundexception: javax.servlet.se-CSDN博客

基于SpringBoot3从零配置SpringDoc_springdoc 配置-CSDN博客

Springboot整合Swagger3全注解配置(springdoc-openapi-ui)_springdoc 注解-CSDN博客

 

posted @ 2024-03-25 18:23  ChantMyZeal  阅读(3996)  评论(0编辑  收藏  举报