遗留Spring MVC引入Spring Boot Fat-Jar后请求映射异常求助
问题背景与现象
- 维护遗留Spring MVC项目,引入一个基于spring-boot-starter构建、用于数据库操作的fat-jar
- 该jar作为依赖加入主项目pom后,出现请求映射错误:
No mapping found for HTTP request with URI [/api/user] in DispatcherServlet with name...,移除jar后主项目恢复正常 - 当前Spring Boot项目使用maven-assembly-plugin打包,配置如下:
<plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-assembly-plugin</artifactId> <configuration> <descriptorRefs> <descriptorRef>jar-with-dependencies</descriptorRef> </descriptorRefs> </configuration> <executions> <execution> <id>make-assembly</id> <phase>package</phase> <goals> <goal>single</goal> </goals> </execution> </executions> </plugin>
解决方案
1. 停止使用Fat-Jar打包
maven-assembly-plugin打出的jar-with-dependencies会把Spring Boot所有依赖(包括Spring核心、DispatcherServlet类)打包进jar,和遗留Spring MVC项目的依赖版本冲突,导致DispatcherServlet映射规则被覆盖或加载异常。
Spring Boot组件作为依赖给其他项目使用时,必须打普通可依赖Jar(仅包含自身代码和依赖声明,不打包依赖包)。
2. 修改打包配置
改用Spring Boot官方插件spring-boot-maven-plugin,配置打包为普通可依赖Jar:
<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)和可执行Fat-Jar(带exec后缀) --> <classifier>exec</classifier> </configuration> </execution> </executions> </plugin>
打包后,将不带exec后缀的普通Jar引入遗留项目即可。
3. 严格控制组件扫描范围
在Spring Boot数据库组件的配置类中,限定扫描范围仅包含自身包,避免干扰遗留项目上下文:
@Configuration @ComponentScan(basePackages = "com.your.db.component.package") @EnableJpaRepositories(basePackages = "com.your.db.component.package") @EntityScan(basePackages = "com.your.db.component.package") public class DbComponentAutoConfiguration { // 组件配置逻辑 }
同时确保遗留项目的Spring配置不扫描该组件包,或明确指定自身扫描范围。
4. 对齐依赖版本
检查遗留Spring MVC项目与Spring Boot组件的Spring核心版本兼容性,尽量保持两者版本一致或兼容,避免版本差异导致的上下文初始化问题。
内容的提问来源于stack exchange,提问作者Felipe Leite Vitorino
相关产品推荐
相关产品推荐

