Swagger访问路径添加前缀

小灰灰 2023-10-04 12:27 111阅读 0赞

预期效果

默认访问路径:http://ip:port`/swagger-ui.html`

可自由设置前缀,比如/qianzhui,那么访问路径为:http://ip:port`/qianzhui` /swagger-ui.html

实现

自定义前缀的属性:swagger.prefix,配置该属性的值,即可实现Swagger访问路径添加前缀。

静态资源通过ResourceHandler定义访问路径;接口则通过RedirectViewController重定向。

  1. import org.springframework.beans.factory.annotation.Value;
  2. import org.springframework.context.annotation.Configuration;
  3. import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
  4. import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
  5. import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
  6. /**
  7. * @author markix
  8. */
  9. @Configuration
  10. public class SwaggerPrefixConfiguration implements WebMvcConfigurer {
  11. @Value("${swagger.prefix:}")
  12. private String swaggerPrefix;
  13. @Override
  14. public void addResourceHandlers(ResourceHandlerRegistry registry) {
  15. if (isPrefixSet()) {
  16. registry.addResourceHandler(swaggerPrefix + "/swagger-ui.html*").addResourceLocations("classpath:/META-INF/resources/");
  17. registry.addResourceHandler(swaggerPrefix + "/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
  18. }
  19. }
  20. @Override
  21. public void addViewControllers(ViewControllerRegistry registry) {
  22. if (isPrefixSet()) {
  23. registry.addRedirectViewController(swaggerPrefix + "/v2/api-docs", "/v2/api-docs").setKeepQueryParams(true);
  24. registry.addRedirectViewController(swaggerPrefix + "/swagger-resources", "/swagger-resources");
  25. registry.addRedirectViewController(swaggerPrefix + "/swagger-resources/configuration/ui", "/swagger-resources/configuration/ui");
  26. registry.addRedirectViewController(swaggerPrefix + "/swagger-resources/configuration/security", "/swagger-resources/configuration/security");
  27. registry.addRedirectViewController("/swagger-ui.html", "/404");
  28. }
  29. }
  30. private boolean isPrefixSet() {
  31. return swaggerPrefix != null && !"".equals(swaggerPrefix) && !"/".equals(swaggerPrefix);
  32. }
  33. /* @Override
  34. public void configurePathMatch(PathMatchConfigurer configurer) {
  35. configurer.addPathPrefix(swaggerPrefix, clazz -> clazz.isAssignableFrom(ApiResourceController.class));
  36. }*/
  37. }

reference:
SpringBoot集成Swagger

发表评论

表情:
评论列表 (有 0 条评论,111人围观)

还没有评论,来说两句吧...

相关阅读

    相关 swagger添加访问密码

    [swagger][]现在是很普遍使用的接口文档。 但当项目发布到正式环境之后,swagger暴露给外部是很致命的,因此可以使用添加用户密码访问 (也可以设置swagger