Spring Boot资源获取失败:class path resource cannot be opened because it does not exist

一、问题背景

在配置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();
    }

修改后重新启动项目,正常运行,无报错。

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值