今天在根据硬编码路径找扫描对应文件时候出现
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包为根路径去索引