一、资源抽象接口Resource
Spring使用Resource
装载各种资源,包括配置文件资源、国际化属性文件资源等。Resource
接口位于org.springframework.core.io
包下,继承interface Resource extends InputStreamSource
,主要方法包含:
/**
* Determine whether this resource actually exists in physical form.
* <p>This method performs a definitive existence check, whereas the
* existence of a {@code Resource} handle only guarantees a valid
* descriptor handle.
*/
boolean exists();
/**
* Indicate whether this resource represents a handle with an open stream.
* If {@code true}, the InputStream cannot be read multiple times,
* and must be read and closed to avoid resource leaks.
* <p>Will be {@code false} for typical resource descriptors.
*/
default boolean isOpen() {
return false;
}
/**
* Return a URL handle for this resource.
* @throws IOException if the resource cannot be resolved as URL,
* i.e. if the resource is not available as descriptor
*/
URL getURL() throws IOException;
/**
* Return a File handle for this resource.
* @throws java.io.FileNotFoundException if the resource cannot be resolved as
* absolute file path, i.e. if the resource is not available in a file system
* @throws IOException in case of general resolution/reading failures
* @see #getInputStream()
*/
File getFile() throws IOException;
Resource
的具体实现类:
二、资源加载
- 资源地址表达式
- Spring支持资源类型前缀:
classpath:
还可以成classpath*:
,表示从多个模块中加载。例如:classpath*:com/demo/module*.xml
表示加载com/demo/
下的多个模块,而classpath:com/demo/module*.xml
表示加载com/demo/
下的多个module
开头,.xml
结尾的配置文件。 - 资源路径匹配符
- 资源加载器
ResourcePatternResolver
接口:继承interface ResourcePatternResolver extends ResourceLoader
,支持带资源类型前缀及Ant风格的表达式。PathMatchingResourcePatternResolver
类:实现class PathMatchingResourcePatternResolver implements ResourcePatternResolver
,为Spring提供的标准实现类。- Tips:项目打包后生成jar时,使用
ResourceLoader().getResource(“classpath:<your_path>”).getFile()
可能会抛出FileNotFoundException,可以采用ResourceLoader().getResource(“classpath:<your_path>”).getInputStream()
方法读取。