正确姿势👇
@Bean
public SqlSessionFactory sqlSessionFactory(DataSource idleDataSource) throws Exception {
SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
factoryBean.setDataSource(idleDataSource);
factoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath*:mapper/**/*.xml"));
return factoryBean.getObject();
}
一定要用 new PathMatchingResourcePatternResolver().getResources("classpath:mapper//.xml");!
getResources(),有个 s !
区别在于
- PathMatchingResourcePatternResolver#getResource(String location)
直接把传入的字符串当作资源地址来加载,只会加载一个资源。
@Override
public Resource getResource(String location) {
return getResourceLoader().getResource(location);
}
- PathMatchingResourcePatternResolver#getResources(String locationPattern)
任务传入的是一个资源地址表达式,可能会解析出多个资源并返回资源数组。
@Override
public Resource[] getResources(String locationPattern) throws IOException {
Assert.notNull(locationPattern, "Location pattern must not be null");
if (locationPattern.startsWith(CLASSPATH_ALL_URL_PREFIX)) {
// a class path resource (multiple resources for same name possible)
if (getPathMatcher().isPattern(locationPattern.substring(CLASSPATH_ALL_URL_PREFIX.length()))) {
// a class path resource pattern
return findPathMatchingResources(locationPattern);
}
else {
// all class path resources with the given name
return findAllClassPathResources(locationPattern.substring(CLASSPATH_ALL_URL_PREFIX.length()));
}
}
else {
// Generally only look for a pattern after a prefix here,
// and on Tomcat only after the "*/" separator for its "war:" protocol.
int prefixEnd = (locationPattern.startsWith("war:") ? locationPattern.indexOf("*/") + 1 :
locationPattern.indexOf(':') + 1);
if (getPathMatcher().isPattern(locationPattern.substring(prefixEnd))) {
// a file pattern
return findPathMatchingResources(locationPattern);
}
else {
// a single resource with the given name
return new Resource[] {getResourceLoader().getResource(locationPattern)};
}
}
}
网友评论