Spring Boot 中自定义swagger-ui的URL(path)和样式(UI)

背景:

Spring Boot写的API需要用到的Swagger-ui.html API文档页面,但自动生成的页面,会包含swagger等信息,不是很友好,希望增加我们自己的Logo,以及修改UI style。


解决:

这里不再重复如何配置swagger,网上已经很多教程。

下面是设置自定义HTML和自定义URL(以/v1/api-docs为例)的教程:

  1. 首先到github的swagger-ui 项目中下载dist文件夹里面的所有文件(https://github.com/swagger-api/swagger-ui/tree/master/dist),放到spring-boot的resources/swagger/文件夹中。
    在这里插入图片描述
  2. 在appilication.yml文件中增加如下配置
springfox:
  documentation:
    swagger:
      v2:
        path: /v1/api-docs
  1. 再在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/");
    }
}
  1. 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();
    }

}
  1. 最后打开https://localhost/v1/api-docs/index.html,即可看到最新的UI,想要修改样式到resource/swagger中修改相关的JS和CSS文件即可!(我自己就加了Logo,删了搜索库,改了header为白色(如下图,原谅打码))

在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值