今天使用idea建立maven项目遇到一个很奇怪的bug
在使用MapperScannerConfigurer和SqlSessionFactoryBean对mapper进行配置时出现了bug
配置如下:
<!-- 配置SqlSessionFactoryBean -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<!-- <property name="configLocation" value="classpath:conf.xml" />-->
<property name="mapperLocations" value="classpath:com/my/mapper/studentInfoMapper.xml"></property>
</bean>
<!-- 配置MapperScannerConfigurer,DAO接口所在包名,Spring会自动查找其下的类(相当于配了bean) -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
<property name="basePackage" value="com.my.mapper" />
</bean>
bug如下:
org.springframework.context.support.AbstractApplicationContext.refresh Exception
encountered during context initialization - cancelling refresh attempt:
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'studentInfoService': Unsatisfied dependency expressed through field
'studentInfoMapper'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name
'studentInfoMapper' defined in file
[D:\IDEA\MavenProject\mavenTest03\target\mavenTest03\WEB-
INF\classes\com\my\mapper\StudentInfoMapper.class]: Cannot resolve reference to bean
'sqlSessionFactory' while setting bean property 'sqlSessionFactory'; nested exception is
org.springframework.beans.factory.BeanCreationException: Error creating bean with name
'sqlSessionFactory' defined in URL
[file:/D:/IDEA/MavenProject/mavenTest03/target/mavenTest03/WEB-
INF/classes/applicationContext.xml]: Invocation of init method failed; nested exception is
org.springframework.core.NestedIOException: Failed to parse mapping resource: 'class path
resource [com/my/mapper/studentInfoMapper.xml]'; nested exception is
java.io.FileNotFoundException: class path resource [com/my/mapper/studentInfoMapper.xml]
cannot be opened because it does not exist
在接口名和mapper文件名相同的情况下,出现这样的错误很奇怪,经过排查,发现在idea中配置maven项目时,resources路径并没有自动装配,所以会导致mapper.xml文件失效。
解决方法如下:
在pom.xml中进行如下配置:
<build>
<!-- 如果不进行此配置,mybatis的mapper.xml文件都会被漏掉。 -->
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
</resources>
</build>
再者就是配置文件的准确性(配置属性“mapperLocations”时路径前面必须加上classpath或者classpath*):
<!-- 配置SqlSessionFactoryBean -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<!-- <property name="configLocation" value="classpath:conf.xml" />-->
<property name="mapperLocations" value="classpath:com/my/mapper/studentInfoMapper.xml"></property>
</bean>