4.4 The ResourceLoader

リソースを取得する責務を表すインタフェースです。


public interface ResourceLoader {
Resource getResource(String location);
}

ApplicationContextは全てResourceLoaderを実装する。そのため全てのアプリケーションコンテキストからResourceを取得できる。あるApplicationContextのgetResourceを呼び出した際に、指定したパスの文字列にprefixが付いていない場合は、ApplicationContextに対応するResourceの実装クラスのインスタンスを生成する。


例えばClassPathXmlApplicationContext の例を考える。


ClassPathXmlApplicationContext ctx = ...;
Resource template = ctx.getResource("some/resource/path/myTemplate.txt");
この場合はClassPathResourceがインスタンス化される。


もしFileSystemXmlApplicationContextの場合は


FileSystemXmlApplicationContext ctx = ...;
Resource template = ctx.getResource("some/resource/path/myTemplate.txt");
この場合はFileSystemResourceがインスタンス化される。


また


WebApplicationContext ctx = ...;
Resource template = ctx.getResource("some/resource/path/myTemplate.txt");
この場合はServletContextResourceがインスタンス化される。みたいな感じです。


逆にclasspath:などのprefixを指定した場合は、ApplicationContextの種類に関わらず、必ずprfeixに対応したクラスであるClassPathResourceがインスタンス化される。


Resource template = ctx.getResource("classpath:some/resource/path/myTemplate.txt");


この場合はUrlResource。


Resource template = ctx.getResource("file:/some/resource/path/myTemplate.txt");
Resource template = ctx.getResource("http://myhost.com/resource/path/myTemplate.txt");


PrefixとResourceクラスの対応付けを、表に纏めるとこんな感じになる。

PrefixExampleExplanation
classpath:classpath:com/myapp/config.xmlクラスパスからロード
file:file:/data/config.xmlURLクラスを使って、ファイルシステムにアクセス*1
http:http://myserver/logo.pngURLクラスを使ってロード
指定なし/data/config.xmlApplicationContextの実装クラスごとに異なる

*1:4.7.3 FileSystemResource caveats参照