1.swagger访问404异常
主要原因:访问swagger的路径错误
错误路径:http://localhost:8201/swagger2-ui.html
此路径是我参照学习资料上的图片路径,过于相信所谓的学习资料,资料也是人写的也会出错
正确路径:http://localhost:8201/swagger-ui.html
2.swagger无法正确显示接口
主要原因:未正确设置swagger配置类中对应的controller所对应的扫描的包路径,导致一直没有扫描到对应的包,导致无法正确的显示接口
错误代码示例:
@Configuration
@EnableSwagger2
public class Swagger2Config {
@Value("${info.appName}")
private String title;
@Value("${info.version}")
private String version;
@Value("${info.appDesc}")
private String description;
@Bean
public Docket adminApiConfig() {
return new Docket(DocumentationType.SWAGGER_2)
.groupName("adminApi")
.apiInfo(adminApiInfo())
.select()
//只显示admin路径下的页面
.paths(Predicates.and(PathSelectors.regex("此处未正确修改!")))
.build();
}
private ApiInfo adminApiInfo() {
return new ApiInfoBuilder()
.title("后台管理系统-API文档")
.description("本文档描述了后台管理系统微服务接口定义")
.version("1.0")
.contact(new Contact("atguigu", "http://atguigu.com", "123@qq.com"))
.build();
}
@Bean
public Docket webApiConfig() {
return new Docket(DocumentationType.SWAGGER_2)
.groupName("webApi")
.apiInfo(webApiInfo())
.select()
//只显示api路径下的页面
.paths(Predicates.and(PathSelectors.regex("/api/.*")))
.build();
}
private ApiInfo webApiInfo() {
return new ApiInfoBuilder()
.title("网站-API文档")
.description("本文档描述了网站微服务接口定义")
.version("1.0")
.contact(new Contact("atguigu", "http://atguigu.com", "123@qq.com"))
.build();
}
正确代码示例:
import org.springframework.beans.factory.annotation.Value;
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.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
/**
* @Author: zhangheng
* @Date: 2023/8/1011:18
* @Description:swagger配置类
* @Version:1.0.0
*/
@Configuration
@EnableSwagger2
public class Swagger2Config {
@Value("${info.appName}")
private String title;
@Value("${info.version}")
private String version;
@Value("${info.appDesc}")
private String description;
@Bean
public Docket createRestApi(){
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.atshanghai.yygh"))
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo(){
return new ApiInfoBuilder()
.title(title)
.description(description)
.version(version)
.build();
}
}
二者的主要区别在于,设置Docket().apis()中的包路径没有正确设置,只是一味的抄代码
3.swagger显示的标题页面出现中文乱码
在网上查阅了资料得知,springboot在读取后缀为properties的配置文件时使用的UNICODE编码格式,而我使用的UTF-8导致的编码解码格式不统一而出现的中文乱码,此处参考以下博客的文章Swagger网页Title中文乱码问题_swagger 乱码_衣冠楚楚的绅士的博客-CSDN博客
如果看到这里了,希望您能给我点个赞再走,您的支持是我最大的动力~