一、问题背景
在配置SpringBoot多数据源时,报mapper.xml文件找不到,但是看了编译后的目录下确实有文件。
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.apache.ibatis.session.SqlSessionFactory]: Factory method 'sqlSessionFactory' threw exception; nested exception is org.springframework.core.NestedIOException: Failed to parse mapping resource: 'class path resource [mapper/db01/*Mapper.xml]'; nested exception is java.io.FileNotFoundException: class path resource [mapper/db01/*Mapper.xml] cannot be opened because it does not exist
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:185)
at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:622)
... 42 common frames omitted
Caused by: org.springframework.core.NestedIOException: Failed to parse mapping resource: 'class path resource [mapper/db01/*Mapper.xml]'; nested exception is java.io.FileNotFoundException: class path resource [mapper/db01/*Mapper.xml] cannot be opened because it does not exist
at org.mybatis.spring.SqlSessionFactoryBean.buildSqlSessionFactory(SqlSessionFactoryBean.java:595)
at org.mybatis.spring.SqlSessionFactoryBean.afterPropertiesSet(SqlSessionFactoryBean.java:475)
at org.mybatis.spring.SqlSessionFactoryBean.getObject(SqlSessionFactoryBean.java:615)
二、解决方法
百度看了很多帖子,依然没有解决,最后仔细看获取xml的方法时发现用错了
public SqlSessionFactory sqlSessionFactory(@Qualifier("db02DataSource") DataSource dataSource) throws Exception {
SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
sqlSessionFactoryBean.setDataSource(dataSource);
sqlSessionFactoryBean.setMapperLocations(
new PathMatchingResourcePatternResolver().getResource("classpath:/mapper/db02/*Mapper.xml"));
return sqlSessionFactoryBean.getObject();
}
getResource方法中少了一个s,正确的方法是getResources
- getResource:获取文件系统文件、从类路径下获取指定的文件
- getResources:获取所有类路径下的指定文件、使用通配符获取满足某种格式的文件
public SqlSessionFactory sqlSessionFactory(@Qualifier("db02DataSource") DataSource dataSource) throws Exception {
SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
sqlSessionFactoryBean.setDataSource(dataSource);
sqlSessionFactoryBean.setMapperLocations(
new PathMatchingResourcePatternResolver().getResources("classpath:/mapper/db02/*Mapper.xml"));
return sqlSessionFactoryBean.getObject();
}
修改后重新启动项目,正常运行,无报错。