4.4 The ResourceLoader
リソースを取得する責務を表すインタフェースです。
public interface ResourceLoader {
Resource getResource(String location);
}ApplicationContextは全てResourceLoaderを実装する。そのため全てのアプリケーションコンテキストからResourceを取得できる。あるApplicationContextのgetResourceを呼び出した際に、指定したパスの文字列にprefixが付いていない場合は、ApplicationContextに対応するResourceの実装クラスのインスタンスを生成する。
例えばClassPathXmlApplicationContext の例を考える。
この場合はClassPathResourceがインスタンス化される。
ClassPathXmlApplicationContext ctx = ...;
Resource template = ctx.getResource("some/resource/path/myTemplate.txt");
もしFileSystemXmlApplicationContextの場合は
この場合はFileSystemResourceがインスタンス化される。
FileSystemXmlApplicationContext ctx = ...;
Resource template = ctx.getResource("some/resource/path/myTemplate.txt");
また
この場合はServletContextResourceがインスタンス化される。みたいな感じです。
WebApplicationContext ctx = ...;
Resource template = ctx.getResource("some/resource/path/myTemplate.txt");
逆に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クラスの対応付けを、表に纏めるとこんな感じになる。
Prefix Example Explanation classpath: classpath:com/myapp/config.xml クラスパスからロード file: file:/data/config.xml URLクラスを使って、ファイルシステムにアクセス*1 http: http://myserver/logo.png URLクラスを使ってロード 指定なし /data/config.xml ApplicationContextの実装クラスごとに異なる
*1:4.7.3 FileSystemResource caveats参照