【Spring】Spring 通配符加载Resource文件

Spring 通配符加载Resource文件

SpringResource继承自InputStreamSource

其中InputStreamSource接口定义了获取java.io.InputStream流的规范

InputStreamSource

1
2
3
4
5
6
7
8
9
10
public interface InputStreamSource {
/**
* 返回{@link InputStream}
* 每次调用都创建新的steram
* @return the input stream for the underlying resource (必须不为{@code null})
* @throws java.io.FileNotFoundException 如果resource不存在抛出异常
* @throws IOException 如果无法打开抛出IO异常
*/
InputStream getInputStream() throws IOException;
}

对于Resource定义了操作资源文件的一些基本规范

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
public interface Resource extends InputStreamSource {
boolean exists();
default boolean isReadable() {
return exists();
}
default boolean isOpen() {
return false;
}
default boolean isFile() {
return false;
}
URL getURL() throws IOException;
URI getURI() throws IOException;
File getFile() throws IOException;
default ReadableByteChannel readableChannel() throws IOException {
return Channels.newChannel(getInputStream());
}
long contentLength() throws IOException;
long lastModified() throws IOException;
Resource createRelative(String relativePath) throws IOException;
@Nullable
String getFilename();
String getDescription();
}

Spring中加载资源文件主要是ResourceLoader接口,里面定义了获取资源以及类加载器的规范
ResourceLoader

1
2
3
4
5
6
7
8
public interface ResourceLoader {
/** Pseudo URL prefix for loading from the class path: "classpath:". */
String CLASSPATH_URL_PREFIX = ResourceUtils.CLASSPATH_URL_PREFIX;

Resource getResource(String location);

ClassLoader getClassLoader();
}

Spring中的所有资源加载都是在该接口的基础上实现的

对于通配符加载多个Resource文件的主要是
ResourcePatternResolver

1
2
3
4
5
public interface ResourcePatternResolver extends ResourceLoader {
String CLASSPATH_ALL_URL_PREFIX = "classpath*:";

Resource[] getResources(String locationPattern) throws IOException;
}

通过getResources()方法即可匹配多个

比较常用的实现类为PathMatchingResourcePatternResolver

以下为配置mybatisSqlSessionFactoryBean时,设置MapperLocations的使用

1
2
3
4
5
6
7
8
@Bean
public SqlSessionFactoryBean sqlSessionFactoryBean(DataSource dataSource) throws IOException {
final SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
sqlSessionFactoryBean.setDataSource(dataSource);
final PathMatchingResourcePatternResolver pathMatchingResourcePatternResolver = new PathMatchingResourcePatternResolver();
sqlSessionFactoryBean.setMapperLocations(pathMatchingResourcePatternResolver.getResources("classpath:mapper/*.xml"));
return sqlSessionFactoryBean;
}