工程代码不编译src的java目录下的xml文件问题及解决

IDEA的maven项目中,默认源代码目录下(src/main/java目录)的xml等资源文件并不会在编译的时候一块打包进classes文件夹,而是直接舍弃掉。如果使用的是Eclipse,Eclipse的src目录下的xml等资源文件在编译的时候会自动打包进输出到classes文件夹。

示例:

当在IDEA中使用MyBatis时,一般会创建一个SQL映射的配置文件,这个文件如果是在src/main/java目录下,编译后在target目录下是找不到这个文件的

图片描述

对于IDEA的这个问题,有如下的解决办法:

第一种方法:如果没有特殊业务,不需要指定资源文件定位到src/main/java下,则可以在src下创建main/resources目录,并将所需要的xml资源文件放置其中即可。maven工具默认在编译的时候,会将resources文件夹中的资源文件一块打包进classes目录中。

图片描述

对于MyBatis的这种使用方式,我们必须在配置文件中指定mapper.xml文件的位置,例如在springboot项目中,在application.properties中增加:

mybatis.mapper-locations=classpath:mapper/*.xml

如果是普通的ssm项目,则这样配置:

<bean id="sqlSessionFactoryBean" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="druidDataSource"/> <property name="configLocation" value="classpath:mybatis-config.xml"/> <!-- 配置mapper文件的位置 --> <property name="mapperLocations" value="classpath:mapper/*.xml"/> </bean>

第二种方法:配置maven的pom文件配置,在pom文件中找到<build>节点,添加下列代码:

 
<build>  
  <resources>  
    <!-- mapper.xml文件在java目录下 -->
    <resource> <directory>src/main/java</directory> <includes> <include>**/*.xml</include> </includes> </resource> <!-- mapper.xml文件在resources目录下--> <--<resource> <directory>src/main/resources</directory> </resource>--> </resources> </build>

猜你喜欢

转载自www.cnblogs.com/exmyth/p/11184271.html
今日推荐