完整代碼在最后
一、報錯
1.網(wǎng)頁報錯4042.代碼報錯
No mapping for GET /swagger-ui.html
二、解決辦法
1.版本回退
之前用的是swagger3.0.0和springboot3.0.6,始終沒找到合適的解決辦法,故將版本回退至swagger2.9.2和springboot2.7.11
2.Spring Boot 2.6.X后與Swagger有版本沖突問題,需要在application.properties文件中寫入spring.mvc.pathmatch.matching-strategy=ant_path_matcher
3.重寫父類方法
在SwaggerConfig配置類中繼承WebMvcConfigurer,然后重寫addResourceHandlers方法
public class SwaggerConfig implements WebMvcConfigurer {
// 重寫父類方法
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("swagger-ui.html")
.addResourceLocations("classpath:/META-INF/resources/");
registry.addResourceHandler("/webjars/**")
.addResourceLocations("classpath:/META-INF/resources/webjars/");
}
}
3.以上配置完親測可用
小插曲:之前繼承的是WebMvcConfigurationSupport,導(dǎo)致瀏覽器無法顯示中文,我也是新手入門沒搞懂為什么,換繼承WebMvcConfigurer后完美解決。文章來源:http://www.zghlxwxcb.cn/news/detail-516655.html
三、完整代碼文章來源地址http://www.zghlxwxcb.cn/news/detail-516655.html
package com.example.bsdemo.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
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 springfox.documentation.swagger2.annotations.EnableSwagger2;
//告訴Spring容器,這個類是一個配置類
@Configuration
//啟用Swagger2功能
@EnableSwagger2
public class SwaggerConfig implements WebMvcConfigurer {
// 重寫父類方法
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("swagger-ui.html")
.addResourceLocations("classpath:/META-INF/resources/");
registry.addResourceHandler("/webjars/**")
.addResourceLocations("classpath:/META-INF/resources/webjars/");
}
// 配置Swagger2相關(guān)的bean
@Bean
public Docket createRestApi(){
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com")) //com包下所有API都交給Swagger2管理
.paths(PathSelectors.any()).build();
}
// 此處主要是API文檔頁面顯示信息
private ApiInfo apiInfo(){
return new ApiInfoBuilder()
.title("演示項目API") //標(biāo)題
.description("學(xué)習(xí)Swagger2的演示項目") //描述
.version("1.0") //版本
.build();
}
}
到了這里,關(guān)于【JAVA swagger】解決No mapping for GET /swagger-ui.html報錯的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!