目录
报错
IOException parsing XML document from class path resource [applicationContext.xml];等情况
原因
当xml在resources的下级目录时一切正常,会默认将resources下的文件编译进target目录。但xml文件在java文件夹下时,需要人工将该java文件夹下的所有xml文件也需要编译到target目录中。
因为java程序运行过程中是直接加载target目录中编译好的程序进行执行的!
解决(3种方案)
1. 添加 修改资源路径(推荐)
需要手动在pom.xml的build中添加如下代码,
添加完后记得点击“加载Maven变更”的刷新按钮。
注意:这里是覆盖原有的资源编译目录,而不是添加新的资源编译目录,因此需要在添加新的资源编译目录后重新指定旧的资源编译目录。也就是说只要增加新的需要编译的目录,除.java文件所在目录,所有需要编译的目录都需要重新指定。
建议:修改pom文件后,将项目target下的字节码文件clean掉,再重新compile,查看是否对所有预期目标进行编译。
<resources>
<!-- 手动指定java文件夹为resources文件夹-->
<!-- 当xml文件在java文件夹而不在resources文件夹时,该xml文件不能被编译进target目录,-->
<!-- 又因为代码在执行时是执行的target中编译过的文件,所以加载不到该xml文件。因此必须进行指定。-->
<resource>
<directory>src/main/java</directory>
<includes>
<!-- 指定java文件夹下子包中的所有.xml文件-->
<include>**/*.xml</include>
</includes>
</resource>
<!-- 上述的指定是将原有的编译资源resources目录覆盖掉了,而不是添加编译目录,因此需要补充原有的编译资源目录-->
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.*</include>
</includes>
</resource>
<!-- 有webapp的Maven工程也需要重新指定webapp这个目录-->
<!-- <resource>-->
<!-- <directory>src/main/webapp</directory>-->
<!-- <targetPath>META-INF/resources</targetPath>-->
<!-- <includes>-->
<!-- <include>*.*</include>-->
<!-- </includes>-->
<!-- </resource>-->
</resources>
2. 在resources目录中放xml文件
2.1 在resources目录中创建java目录下的同款目录结构放xml文件
在resources目录中创建的同款目录下放入xml文件,在编译到target目录时,会将java和resources中同样目录结构下的内容编译到一个文件夹中。
2.2 在resources目录的其他位置放置映射文件xml
当使用springboot时,此时需要在application.properties中指定mybatis映射文件的路径(例如放在resources/mapper/StudentMapper.xml)
mybatis.mapper-locations=classpath:mapper/*.xml
3. 在target目录中手动复制xml文件(不推荐)
或者按照下面链接方法解决(不灵活)
https://www.jianshu.com/p/8b402972d0cc