2. Resources
2.1. Introduction
闡述java.net.URL的種種缺點硝岗,說明其不足以用來描述所有資源可都。
2.2. The Resource Interface
針對資源訪問胳岂,Spring定義了自己的接口:
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();
}
public interface InputStreamSource {
InputStream getInputStream() throws IOException;
}
接口相關(guān)重要方法說明:
- getInputStream(): Locates and opens the resource, returning an InputStream for reading from the resource. It is expected that each invocation returns a fresh InputStream. It is the responsibility of the caller to close the stream.
- exists(): Returns a boolean indicating whether this resource actually exists in physical form.
- isOpen(): Returns a boolean indicating whether this resource represents a handle with an open stream. If true, the InputStream cannot be read multiple times and must be read once only and then closed to avoid resource leaks. Returns false for all usual resource implementations, with the exception of InputStreamResource.
- getDescription(): Returns a description for this resource, to be used for error output when working with the resource. This is often the fully qualified file name or the actual URL of the resource.
Spring在很多情況下都用了Resource接口高帖。即使用戶不使用Spring框架稿饰,Spring也非常推薦Resource接口及其相關(guān)實現(xiàn)作為java的資源訪問的替代方案锦秒,雖然這樣跟Spring產(chǎn)生了耦合,但是用起來相當(dāng)于引入了第三方庫喉镰,沒有什么負(fù)面影響旅择。
2.3. Built-in Resource Implementations
Spring包含以下Resource的默認(rèn)實現(xiàn):
2.4. The ResourceLoader
public interface ResourceLoader {
Resource getResource(String location);
}
所有application contexts都實現(xiàn)了ResourceLoader接口,所以可以通過自動裝配的將ResourceLoader直接注入到bean中使用侣姆。同時生真,application contexts都具有g(shù)etResource()方法,可以直接調(diào)用捺宗。ApplicationContext的getResource()方法的返回類型為2.3中提到的幾種類型柱蟀。有兩種方式可以決定返回的Resource類型:1,資源前綴classpath或者file等蚜厉;2长已,在沒有資源前綴的情況下,由ApplicationContext類型決定弯囊,比如ClassPathXmlApplicationContext痰哨,在不指定資源前綴的情況下,返回ClassPathResource類型匾嘱。
Resource template = ctx.getResource("some/resource/path/myTemplate.txt");
Resource template = ctx.getResource("classpath:some/resource/path/myTemplate.txt");
Resource template = ctx.getResource("file:///some/resource/path/myTemplate.txt");
Resource template = ctx.getResource("http://myhost.com/resource/path/myTemplate.txt");
2.5. The ResourceLoaderAware interface
可以通過繼承ResourceLoaderAware接口斤斧,由Spring注入ResourceLoader。不過推薦直接使用@Autowired霎烙,更方便撬讽。
public interface ResourceLoaderAware {
void setResourceLoader(ResourceLoader resourceLoader);
}
2.6. Resources as Dependencies
可以直接注入Resource類型,Spring會根據(jù)前綴情況自動轉(zhuǎn)換相應(yīng)的Resource類型:
@Data
@Component
public class ResourceBean {
@Autowired
@Value("classpath:app.properties")
private Resource resource;
@Autowired
@Value("file:///app.properties")
private Resource resource1;
}
2.7. Application Contexts and Resource Paths
通配符的使用悬垃,兼容性問題和一些使用注意事項游昼。建議直接看官方文檔。