BestMeのブログ -3ページ目

BestMeのブログ

ブログの説明を入力します。

BeanFactory bf = new XmlBeanFactory(new ClassPathResource("beanFactoryTest.xml"));をきっかけ

ClassPathResource
●背景
javaはリソースをURLに抽象して、handler(URLStreamHandler)を登録してリソースをアクセスするんです。普通のhandlerはProtocolで"file:"、"http:"、"java:"を判明しますが、ClasspathまたはServletContextの相対パスの処理はなかったんです。なので、SpringはInputStreamSourceおよびResourceを定義しました。
・FileSystemResource(ファイル)
・ClasspathResource(Classpathリソース)
・UrlResource(URLリソース)
・InputStreamResource(InputStreamリソース)
・ByteArrayResource(Byteリソース)
●テクニック
 一般の開発の際でも、下記のようにResourceを取り込むことが可能
 Resource resource = new ClassPathResource("beanFactoryTest.xml");
   InputStream inputStream = resource.getInputStream();
   InputStreamを取得できたら、いつものように操作すればOKです。

●ソース
//クラスパスが通っているディレクトリをルートとする相対または絶対指定のリソース
public class ClassPathResource extends AbstractFileResolvingResource {
...
//例はこのコンストラクタを使っています、clazzとclassLoaderを指定なし
//ただ、内部的に、classLoaderはdefaultClassLoaderが指定される
public ClassPathResource(String path) {
this(path, (ClassLoader) null);
}

public ClassPathResource(String path, ClassLoader classLoader) {
Assert.notNull(path, "Path must not be null");
String pathToUse = StringUtils.cleanPath(path);
if (pathToUse.startsWith("/")) {
pathToUse = pathToUse.substring(1);
}
this.path = pathToUse;
//classLoader指定されない場合、Thread.currentThread().getContextClassLoader();をデフォルトとして設定される
this.classLoader = (classLoader != null ? classLoader : ClassUtils.getDefaultClassLoader());
}

protected ClassPathResource(String path, ClassLoader classLoader, Class<?> clazz) {
this.path = StringUtils.cleanPath(path);
this.classLoader = classLoader;
this.clazz = clazz;
}
...

//Resourceインタフェースのコアメソッド
//pathに指定したClazzまたはclassLoaderの相対パスからリソースのInputStreamを返す
public InputStream getInputStream() throws IOException {
InputStream is;
//clazzはコンストラクタより設定される
if (this.clazz != null) {
is = this.clazz.getResourceAsStream(this.path);
}
else if (this.classLoader != null) {
//例だと、Thread.currentThread().getContextClassLoader().getResourceAsStream(this.path)が実際実行される
is = this.classLoader.getResourceAsStream(this.path);
}
else {
is = ClassLoader.getSystemResourceAsStream(this.path);
}
if (is == null) {
throw new FileNotFoundException(getDescription() + " cannot be opened because it does not exist");
}
return is;
}
...
}

//ファイルリソース、もっと簡単、そのままjavaのFileInputStreamを利用した
public class FileSystemResource extends AbstractResource implements WritableResource {
...
public FileSystemResource(String path) {
Assert.notNull(path, "Path must not be null");
this.file = new File(path);
this.path = StringUtils.cleanPath(path);
}
...
public InputStream getInputStream() throws IOException {
return new FileInputStream(this.file);
}
}