springfox swagger-ui多个包路径扫描匹配的改造支持

本文介绍如何在Spring Boot项目中使用Swagger2支持多个模块的API文档生成。通过自定义Docket Bean并重写RequestHandlerSelectors.basePackage方法,实现对多个指定包路径下控制器的API接口进行扫描。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

使用springfox中的 RequestHandlerSelectors.basePackage("com.xxx") 只能支持单个包路径的扫描匹配,

如果要想支持多个包路径的匹配我们需要修改springfox里面的代码来支持他,现做以下修改来支持多包路径匹配。

  1. package com.xxx.swagger;
  2. import org.springframework.beans.factory.annotation.Value;
  3. import org.springframework.context.annotation.Bean;
  4. import org.springframework.context.annotation.Configuration;
  5. import org.springframework.context.annotation.PropertySource;
  6. import org.springframework.context.annotation.PropertySources;
  7. import springfox.documentation.RequestHandler;
  8. import springfox.documentation.builders.ApiInfoBuilder;
  9. import springfox.documentation.builders.PathSelectors;
  10. import springfox.documentation.service.ApiInfo;
  11. import springfox.documentation.spi.DocumentationType;
  12. import springfox.documentation.spring.web.plugins.Docket;
  13. import springfox.documentation.swagger2.annotations.EnableSwagger2;
  14. import com.google.common.base.Function;
  15. import com.google.common.base.Optional;
  16. import com.google.common.base.Predicate;
  17. /**
  18. * Swagger2 UI配置
  19. *
  20. * <pre>
  21. * 通过访问http://your ip:8090/api/swagger-ui.html查看发布的REST接口;
  22. * </pre>
  23. *
  24. * @author 许畅
  25. * @since JDK1.7
  26. * @version 2017年10月19日 许畅 新建
  27. */
  28. @Configuration
  29. @PropertySources({ @PropertySource(value = "classpath:swagger2.properties", ignoreResourceNotFound = true, encoding = "UTF-8") })
  30. @EnableSwagger2
  31. public class Swagger2UIConfig {
  32. /**
  33. * 获取API标题
  34. */
  35. @Value("${swagger2.title}")
  36. public String title = "Spring Boot中使用Swagger2构建Restful API";
  37. /**
  38. * Swagger2创建Docket的Bean
  39. *
  40. * @return Docket
  41. */
  42. @Bean
  43. public Docket createRestApi() {
  44. return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo()).select()
  45. .apis(Swagger2UIConfig.basePackage("com.xxx1,com.xxx2")).paths(PathSelectors.any()).build();
  46. }
  47. /**
  48. * Predicate that matches RequestHandler with given base package name for the class of the handler method.
  49. * This predicate includes all request handlers matching the provided basePackage
  50. *
  51. * @param basePackage - base package of the classes
  52. * @return this
  53. */
  54. public static Predicate<RequestHandler> basePackage(final String basePackage) {
  55. return new Predicate<RequestHandler>() {
  56. @Override
  57. public boolean apply(RequestHandler input) {
  58. return declaringClass(input).transform(handlerPackage(basePackage)).or(true);
  59. }
  60. };
  61. }
  62. /**
  63. * 处理包路径配置规则,支持多路径扫描匹配以逗号隔开
  64. *
  65. * @param basePackage 扫描包路径
  66. * @return Function
  67. */
  68. private static Function<Class<?>, Boolean> handlerPackage(final String basePackage) {
  69. return new Function<Class<?>, Boolean>() {
  70. @Override
  71. public Boolean apply(Class<?> input) {
  72. for (String strPackage : basePackage.split(",")) {
  73. boolean isMatch = input.getPackage().getName().startsWith(strPackage);
  74. if (isMatch) {
  75. return true;
  76. }
  77. }
  78. return false;
  79. }
  80. };
  81. }
  82. /**
  83. * @param input RequestHandler
  84. * @return Optional
  85. */
  86. private static Optional<? extends Class<?>> declaringClass(RequestHandler input) {
  87. return Optional.fromNullable(input.declaringClass());
  88. }
  89. /**
  90. * Swagger2创建该Api的基本信息
  91. *
  92. * @return ApiInfo
  93. */
  94. @Bean
  95. public ApiInfo apiInfo() {
  96. return new ApiInfoBuilder().title(title)
  97. .description("更多Swagger2配置相关文章请关注:https://springfox.github.io/springfox/docs/current/")
  98. .termsOfServiceUrl("https://springfox.github.io/springfox/docs/current/").version("1.0").build();
  99. }
  100. }
<think>好的,我现在要解决用户在Spring Boot项目中引入Swagger后访问swagger-ui.html出现404的问题。根据用户提供的引用内容,我需要综合这些信息,给出有效的解决方案。 首先,用户提到了多个可能的原因和解决方法。我需要逐一分析这些引用中的建议,并整理出步骤清晰的解决方案。 根据引用[1]、[3]、[5],用户可能没有正确添加依赖。比如,用户可能只添加了swagger2而没有swagger-ui,或者版本不一致。因此,检查依赖是否正确是第一步。引用[4]提到使用springfox-boot-starter 3.0.0,这可能是一个更简单的解决方案,因为它可能自动含所需的依赖。不过,用户需要注意版本兼容性,特别是Spring Boot的版本是否支持Swagger的版本。 接下来,引用[2]和[4]都提到了配置类的问题。在SwaggerConfig类中添加资源处理器(ResourceHandlerRegistry)是必要的,因为Spring Boot可能没有正确映射Swagger的静态资源。这需要用户自定义配置类,并确保添加了正确的资源路径。 另外,引用[2]中的代码示例展示了如何覆盖addResourceHandlers方法,将/swagger-ui.html和/webjars/**映射到正确的classpath位置。这可能是因为在Spring Boot 2.X版本中,默认的资源处理方式有所改变,需要手动配置。 另外,用户可能没有启用Swagger的注解,比如在配置类上使用@EnableSwagger2或@EnableSwagger2WebMvc。这可能导致Swagger的端点没有被正确注册。 还需要检查Spring Boot的版本与Swagger版本是否兼容。例如,引用[4]提到的springfox-boot-starter 3.0.0可能需要Spring Boot 2.2以上版本。如果用户使用的是旧版Spring Boot,可能需要降级Swagger版本。 此外,项目的结构也可能影响组件的扫描。如果Swagger配置类不在主应用程序类的子下,可能需要手动配置扫描路径,或者使用@ComponentScan注解。 还有可能用户没有正确配置路径,比如访问的URL是否正确。正确的访问路径应该是http://localhost:端口/swagger-ui.html,而有时候可能需要添加项目上下文路径,特别是在部署到服务器时。 此外,安全配置(如Spring Security)可能会拦截Swagger的请求,需要放行相关路径。例如,在安全配置中允许/swagger-ui.html和/webjars/**的访问。 总结可能的解决步骤: 1. 检查依赖是否正确,尤其是swagger2swagger-ui的版本是否一致,或者是否使用springfox-boot-starter。 2. 创建Swagger配置类,并添加资源处理器。 3. 启用Swagger注解,如@EnableSwagger2。 4. 检查结构,确保配置类被扫描到。 5. 调整安全配置,允许访问Swagger相关路径。 6. 验证访问URL是否正确,括端口和上下文路径。 需要注意,不同版本的Swagger可能有不同的配置方式,特别是Springfox和SpringDoc之间的区别。例如,如果用户使用的是Spring Boot 3.x,可能需要切换到SpringDoc OpenAPI,因为Springfox可能不再兼容。 最后,可能需要清除Maven缓存并重新构建项目,确保依赖正确下载。</think>### Spring Boot中解决swagger-ui.html 404问题的逐步方案 #### 1. 检查依赖配置(关键步骤) 确保`pom.xml`中同时含**swagger2**和**swagger-ui**依赖,且版本一致: ```xml <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>2.9.2</version> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>2.9.2</version> </dependency> ``` 或使用**简化依赖**(Spring Boot 2.2+推荐)[^4]: ```xml <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-boot-starter</artifactId> <version>3.0.0</version> </dependency> ``` #### 2. 创建Swagger配置类 新建`SwaggerConfig.java`,添加资源映射和注解支持: ```java @Configuration @EnableSwagger2 // 或@EnableSwagger2WebMvc public class SwaggerConfig extends WebMvcConfigurationSupport { @Bean public Docket api() { return new Docket(DocumentationType.SWAGGER_2) .select() .apis(RequestHandlerSelectors.basePackage("你的Controller路径")) .paths(PathSelectors.any()) .build(); } @Override protected void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/swagger-ui.html") .addResourceLocations("classpath:/META-INF/resources/"); registry.addResourceHandler("/webjars/**") .addResourceLocations("classpath:/META-INF/resources/webjars/"); } } ``` #### 3. 验证扫描范围 确认配置类所在位于**主启动类同级或子目录**。若不在,需添加扫描注解: ```java @SpringBootApplication @ComponentScan({"com.example.main","com.example.swagger"}) // 手动指定扫描范围 public class Application { ... } ``` #### 4. 检查安全配置 如果项目集成了Spring Security,需放行Swagger路径: ```java @Configuration public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() .antMatchers("/swagger-ui.html", "/webjars/**", "/v2/api-docs").permitAll() ... } } ``` #### 5. 验证访问地址 正确访问路径应为: ``` http://localhost:端口/swagger-ui.html ``` 若配置了`server.servlet.context-path`,需追加上下文路径: ``` http://localhost:端口/上下文路径/swagger-ui.html ``` #### 6. 版本兼容性检查 - Spring Boot 2.6+需添加配置解决路径匹配策略问题: ```properties spring.mvc.pathmatch.matching-strategy=ant_path_matcher ``` - Spring Boot 3.x需改用**SpringDoc OpenAPI**(Springfox已停止维护)[^4]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值