Maven多模块依赖Swagger生成Spring Boot应用编译找不到类求解决方案
Maven多模块依赖Swagger生成Spring Boot模块的编译解决方案
你的判断完全正确——问题出在Swagger生成的模块被打包成了Spring Boot可执行Jar,这种Jar的类文件都放在BOOT-INF/classes目录下,而普通Maven依赖只会扫描Jar根目录下的类,所以第二个模块根本找不到这些类。下面给你几个从优到次的解决方案:
最佳实践:拆分Swagger模块为API层和启动层
这是最符合Maven模块化设计的方案,能彻底避免Jar结构冲突:
- 把原Swagger生成模块拆成两个子模块:
swagger-api:只放Swagger生成的实体类、API接口、DTO等纯代码,不使用Spring Boot打包插件,用普通Maven编译打包(仅保留maven-compiler-plugin即可)。这个模块的Jar是标准的Maven依赖Jar,类直接在根目录。swagger-boot:作为Spring Boot启动模块,依赖swagger-api,只放启动类和Spring Boot配置,用spring-boot-maven-plugin打包成可执行Jar。
- 你的业务扩展模块直接依赖
swagger-api模块,就能正常引用所有生成的类了。
快速适配:让Swagger模块同时生成两种Jar
如果不想拆分模块,可以修改Swagger生成模块的spring-boot-maven-plugin配置,让它同时生成普通依赖Jar和可执行Jar:
在Swagger模块的pom.xml中添加以下配置:
<build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> <executions> <execution> <id>repackage</id> <goals> <goal>repackage</goal> </goals> <configuration> <!-- 给可执行Jar加一个classifier后缀,比如xxx-boot.jar --> <classifier>boot</classifier> </configuration> </execution> </executions> </plugin> </plugins> </build>
打包后会生成两个Jar:
- 不带后缀的
xxx.jar:标准Maven依赖Jar,类在根目录,供其他模块依赖 - 带
-boot后缀的xxx-boot.jar:可执行Spring Boot Jar,用于启动项目
你的业务模块直接依赖这个不带后缀的Jar即可,无需额外配置。
临时 hack 方案(不推荐)
如果以上两种都没法快速实施,可以在业务扩展模块中通过maven-dependency-plugin解压Swagger Jar里的BOOT-INF/classes到编译路径,但这种方式容易引发版本冲突、重复类等问题,仅适合临时调试:
<build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-dependency-plugin</artifactId> <executions> <execution> <id>unpack-swagger-classes</id> <phase>compile</phase> <goals> <goal>unpack</goal> </goals> <configuration> <artifactItems> <artifactItem> <groupId>你的Swagger模块groupId</groupId> <artifactId>你的Swagger模块artifactId</artifactId> <version>对应版本号</version> <outputDirectory>${project.build.directory}/classes</outputDirectory> <includes>BOOT-INF/classes/**</includes> </artifactItem> </artifactItems> </configuration> </execution> </executions> </plugin> </plugins> </build>
父POM注意事项
另外检查下你的父POM,不要全局配置spring-boot-maven-plugin,应该只在需要打包成可执行Jar的模块(比如上面的swagger-boot)中单独配置,避免其他模块被误打包成Spring Boot可执行Jar。
内容的提问来源于stack exchange,提问作者Xtroce
相关产品推荐
相关产品推荐

