Swagger2和SpringBoot整合后找不到swagger-ui.html
情景还原
环境:
包名 | 版本 |
---|---|
SpringBoot | 2.6.3 |
springfox-swagger2 | 3.0.0 |
springfox-swagger-ui | 3.0.0 |
原因:swagger 3.0.0版本在与SpringBoot 2.X进行整合时,不再使用springfox-swagger2
和springfox-swagger-ui
,而应该使用springfox-boot-starter
,这个新的整合包将包含上述两个包的所有依赖,并且移除了@EnableSwagger2
注解
具体细节可见springfox
解决办法
1. 修改项目的pom.xml
文件
用springfox-boot-starter
替换springfox-swagger2
和springfox-swagger-ui
依赖
<dependencies>
<!--整合swagger2和springboot-->
<!--添加新依赖-->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-boot-starter</artifactId>
<version>3.0.0</version>
</dependency>
<!--移除下面两个旧的依赖-->
<!--
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>3.0.0</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>3.0.0</version>
</dependency>
-->
</dependencies>
2. 移除@EnableSwagger2
注解
@Configuration
//@EnableSwagger2 移除这个注解
public class SwaggerConfig {
@Bean
public Docket getDocket(Environment environment){
//设置要启用swagger的环境,也就是说,只有environment扫描到的环境中包含dev或者test时,才启用swagger
Profiles profiles = Profiles.of("dev", "test");
//通过environment.acceptsProfiles方法判断当前是否出在profile所设置的环境当中,该方法返回一个布尔值
boolean flag = environment.acceptsProfiles(profiles);
return new Docket(DocumentationType.SWAGGER_2)
//配置api信息
.apiInfo(getApiInfo())
//设置是否启用swagger,这里的flag由系统根据启动配置文件自动判断
.enable(flag)
//工厂模式选择器设置哪些接口需要被扫描
.select()
// //扫描所有的接口
// .apis(RequestHandlerSelectors.any())
// //不扫描任何接口
// .apis(RequestHandlerSelectors.none())
// //只扫描包含@Controller注解的类
// .apis(RequestHandlerSelectors.withClassAnnotation(Controller.class))
// //只扫描包含@GerMapping注解的方法
// .apis(RequestHandlerSelectors.withMethodAnnotation(GetMapping.class))
//扫描com.mlzhilu.controller包下的所有接口
.apis(RequestHandlerSelectors.basePackage("com.mlzhilu.controller"))
// //扫描匹配 /controller/** 表达式的路径下的所有接口
// .paths(PathSelectors.ant("/controller/**"))
.build();
}
public ApiInfo getApiInfo(){
return new ApiInfo(
"Api 中文文档",
"Api 描述",
"1.0",
"urn:tos",
new Contact(
"mlzhilu",
"mlzhilu.com",
"xxxxxx@163.com"),
"Apache 2.0",
"http://www.apache.org/licenses/LICENSE-2.0",
new ArrayList<>());
}
}
评论区