SpringBoot3專案使用Knife4j時訪問doc.html出現Knife4j文件請求異常且開發者工具網路皮膚中swagger-resources請求出現404的處理心得

ChantMyZeal發表於2024-03-25

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。

相關文章