背景:
Spring Boot写的API需要用到的Swagger-ui.html API文档页面,但自动生成的页面,会包含swagger等信息,不是很友好,希望增加我们自己的Logo,以及修改UI style。
解决:
这里不再重复如何配置swagger,网上已经很多教程。
下面是设置自定义HTML和自定义URL(以/v1/api-docs为例)的教程:
- 首先到github的swagger-ui 项目中下载dist文件夹里面的所有文件(https://github.com/swagger-api/swagger-ui/tree/master/dist),放到spring-boot的resources/swagger/文件夹中。
- 在appilication.yml文件中增加如下配置
springfox:
documentation:
swagger:
v2:
path: /v1/api-docs
- 再在WebMvcConfigurer文件中加入映射的相关配置:
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
//关闭原生swagger-ui, 自动redirect去根目录
registry.addResourceHandler("swagger-ui.html").addResourceLocations("classpath:/");
//新的api document ui
registry.addResourceHandler("/v1/api-docs/**").addResourceLocations("classpath:/swagger/");
}
}
- SwaggerConfig.java配置无需特别修改,以下是我自己的参考:
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Value("${swagger.enable}")
private boolean enableSwagger;
@Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
// default show base information
.apiInfo(apiInfo())
// Set which interfaces are exposed to Swagger for display
.select()
// Scan all annotated APIs
.apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("REST API")
.description("")
.build();
}
}
- 最后打开https://localhost/v1/api-docs/index.html,即可看到最新的UI,想要修改样式到resource/swagger中修改相关的JS和CSS文件即可!(我自己就加了Logo,删了搜索库,改了header为白色(如下图,原谅打码))