SqlSessionFactory的ConfigLocation配置路径索引不到文件

今天在根据硬编码路径找扫描对应文件时候出现

Caused by: java.io.FileNotFoundException: class path resource [classpath*:mapper/*Mapper.xml] cannot be opened because it does not exist
	at org.springframework.core.io.ClassPathResource.getInputStream(ClassPathResource.java:199) ~[spring-core-5.3.18.jar:5.3.18]
	at org.mybatis.spring.SqlSessionFactoryBean.buildSqlSessionFactory(SqlSessionFactoryBean.java:608) ~[mybatis-spring-2.0.5.jar:2.0.5]
	... 58 common frames omitted

大意就是路径字符串未找到对应文件

    @Bean
    public SqlSessionFactory getSqlSessionFactory(@Autowired DataSource dataSource, MybatisProperties mybatisProperties) throws Exception {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSource);
        sqlSessionFactoryBean.setVfs(SpringBootVFS.class);
        sqlSessionFactoryBean.setConfigLocation(new ClassPathResource("mybatis/mybatis-config.xml"));
        sqlSessionFactoryBean.setMapperLocations(new ClassPathResource("classpath*:mapper/*Mapper.xml"));
        return sqlSessionFactoryBean.getObject();
    }```

问题出现在setmapperLocations这个路径未发现文件。
后续发现ClassPathResource这个类是根据当前项目src/main/resources为根路径去寻找文件。

修改如下即可根据路径去索引到对应的文件

    @Bean
    public SqlSessionFactory getSqlSessionFactory(@Autowired DataSource dataSource, MybatisProperties mybatisProperties) throws Exception {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSource);
        sqlSessionFactoryBean.setVfs(SpringBootVFS.class);
        sqlSessionFactoryBean.setConfigLocation(new ClassPathResource("mybatis/mybatis-config.xml"));
        ResourcePatternResolver resourceResolver = new PathMatchingResourcePatternResolver();
        Resource[] resources = resourceResolver.getResources("classpath*:mapper/*Mapper.xml");
        sqlSessionFactoryBean.setMapperLocations(resources);
        return sqlSessionFactoryBean.getObject();
    }

总而言之
ClassPathResource是基于src/main/resources为根路径去索引
PathMatchingResourcePatternResolver是基于target包为根路径去索引

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值