resource
public interface InputStreamSource {
//定位并打开资源,返回一个用于读取资源的InputStream。预期每次调用都会返回一个新的InputStream。调用者负责关闭流
InputStream getInputStream() throws IOException;
}
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
public interface Resource extends InputStreamSource {
//资源是否已物理形式存在
boolean exists();
boolean isOpen();
URL getURL() throws IOException;
File getFile() throws IOException;
Resource createRelative(String relativePath) throws IOException;
String getFilename();
String getDescription();
}
resource 实现类
UrlResource
ClassPathResource
FileSystemResource
ServletContextResource
InputStreamResource
ByteArrayResource
ResourceLoader
所有application contexts都实现了ResourceLoader接口,可以获取资源
public interface ResourceLoader {
//加载并返回资源
Resource getResource(String location);
}
location参数中如果不指定前缀,获取的资源会根据上下文类型确定资源的实现类。
Resource template = ctx.getResource("some/resource/path/myTemplate.txt");
ctx的实现类 | resource的实现类 |
---|---|
ClassPathXmlApplicationContext | ClassPathResource |
FileSystemXmlApplicationContext | FileSystemResource |
WebApplicationContext | ServletContextResource |
也可以强制使用特定类型的resource(location中指定前缀)
location前缀 | resource的实现类 |
---|---|
classpath: | ClassPathResource |
file:、http: | FileSystemResource |
WebApplicationContext | ServletContextResource |
ResourceLoaderAware
类实现这个接口后,容器会调用setResourceLoader方法进行回调,参数是容器本身(容器都实现了ResourceLoader接口)
public interface ResourceLoaderAware {
void setResourceLoader(ResourceLoader resourceLoader);
}
Resources as Dependencies
如果template是Resource类型的参数,可以直接通过字符串注入resource
<bean id="myBean" class="...">
<property name="template" value="some/resource/path/myTemplate.txt"/>
<property name="template" value="classpath:some/resource/path/myTemplate.txt">
</bean>