maven打包时默认未包含xml文件解决方法

本文介绍如何在Maven项目中正确配置MyBatis的XML映射文件,确保它们能够被正确地包含在最终的构建产物中。通过调整pom.xml文件中的资源过滤设置,可以实现XML文件与Java类一同被打包。

在使用MyBatis框架进行项目开发时,经常会打MyBatis的配置文件xml文件放在代码包中。但在使用Maven进行打包时,默认未将这些xml文件拷贝到classes文件夹下。为了解决这个问题,需要在pom.xml文件中添加以下配置: 

<resources>
        	<resource>
        		<directory>src/main/java</directory>
        		<includes>
        			<include>**/*.xml</include>
        		</includes>
        	</resource>
        	<resource>
        		<directory>src/main/resources</directory>
        		<includes>
        			<include>**/*.xml</include>
        			<include>**/*.properties</include>
        		</includes>
        	</resource>
        </resources>

 

clean后再重新打包,xml文件将和class文件一起拷贝到classes文件夹下。

你遇到的问题是:**Maven 没有将 `mapper.xml` 文件打包进最终的 jar 文件中**,这会导致 MyBatis 无法找到对应的 SQL 映射文件,从而抛出 `Invalid bound statement (not found)` 异常。 --- ## ✅ 问题定位 Maven 默认只会将 `src/main/resources` 下的资源文件复制到 `target/classes` 目录下,并最终打包进 jar。如果你的 `mapper.xml` 文件没有放在 `resources` 目录下,或者没有正确配置资源过滤,Maven 就不会将这些文件打包进去。 --- ## ✅ 解决方案 ### ✅ 方法一:将 `mapper.xml` 文件放到 `resources` 目录下 确保你的 XML 文件路径如下: ``` src/main/resources/com/example/jhzx/mapper/Product_InformationMapper.xml ``` 这是最标准的做法,MyBatis 推荐将 XML 文件放在 `resources` 下,以便 Maven 正确打包。 --- ### ✅ 方法二:在 `pom.xml` 中添加资源过滤配置(推荐) 如果你的 `mapper.xml` 文件不在 `resources` 目录下(比如放在了 `src/main/java` 下),你需要手动配置 Maven 将这些文件包含进构建中。 在 `pom.xml` 中添加如下配置: ```xml <build> <resources> <!-- 默认资源目录 --> <resource> <directory>src/main/resources</directory> <includes> <include>**/*.xml</include> </includes> <filtering>true</filtering> </resource> <!-- 如果 mapper.xml 放在 java 目录下,需要额外添加如下配置 --> <resource> <directory>src/main/java</directory> <includes> <include>**/*.xml</include> </includes> </resource> </resources> </build> ``` > ✅ 建议:最好还是将 XML 文件放到 `resources` 下,避免混淆资源与源码。 --- ### ✅ 方法三:验证是否打包成功 构建项目后,使用以下命令查看 jar 包中是否包含 XML 文件: ```bash jar tf target/your-application.jar | grep mapper ``` 你应该能看到类似如下输出: ``` com/example/jhzx/mapper/Product_InformationMapper.xml ``` 如果没有,说明你的配置仍然有问题。 --- ### ✅ 方法四:检查 MyBatis 的 `mapper-locations` 配置 确保你在 `application.yml` 或 `application.properties` 中配置了正确的 XML 路径: #### ✅ application.yml 示例: ```yaml mybatis: mapper-locations: classpath:com/example/jhzx/mapper/*.xml type-aliases-package: com.example.jhzx.entity ``` #### ✅ application.properties 示例: ```properties mybatis.mapper-locations=classpath:com/example/jhzx/mapper/*.xml mybatis.type-aliases-package=com.example.jhzx.entity ``` --- ## ✅ 附加建议 - 使用 `mvn clean package` 构建项目前,先执行 `mvn clean` 确保构建环境干净。 - 可以使用 `target/classes` 目录检查构建后的资源是否正确生成。 - 如果你使用的是 IDE(如 IntelliJ IDEA),记得刷新 Maven 项目,确保配置生效。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值