SpringのResourceについて
#Spring
これを読んだときのメモ
https://docs.spring.io/spring/docs/5.2.7.RELEASE/spring-framework-reference/core.html#resources
URLクラスは低レベルのリソースアクセスに使うには十分な機能を提供していない
classpath内のリソースが読めない
http以外だと複雑な使い方になる
リソースの存在チェックkなどができない
ResouceクラスはInputStreamSourceを継承していて以下のメソッドを提供している
getInputStream
リソースを読み込むためのInputStreamを返す。ストリームを閉じるのは呼び出し元の責任
isOpen
リソースがオープン状態のストリームを持っているかを表すbool値を返す
trueの場合複数回resouceの読み込みはできず、一度オープン状態を閉じなければいけない
getURL, getFile
もし実際のりーソスがURLやFileに変換できるものであればこれらに変換できる
S3のリソースとかはFileに変換しようとしたらエラーになった(たしかUnSupportedException)。対応していないとそのような挙動になるっぽい。
resource実装のうち、InputStreamResourceでしかtrueを返さないっぽい
While the Resource interface is used a lot with Spring and by Spring, it is actually very useful to use as a general utility class by itself in your own code, for access to resources, even when your code does not know or care about any other parts of Spring. While this couples your code to Spring, it really only couples it to this small set of utility classes, which serve as a more capable replacement for URL and can be considered equivalent to any other library you would use for this purpose.
Resource使うことでSpringの依存ははいってしまうわけだど、Springの世界を知らない部分にresouceを持ち込んでも便利に使えるよ (そういう想定をしている) という感じみたい
Built Inのresource実装は以下のようなものがあると (S3のリソース実装どんな感じかは後で見てみよう)
UrlResource
ClassPathResource
FileSystemResource
ServletContextResource
InputStreamResource
基本的にはByteArrayResourceとかを優先して使うべき
他のResouce実装とは異なり、これはすでにOpen状態になっているリソースのための記述し
リソース記述しをどこかに保存しておく場合や複数回読み込む場合は使用するべきではない
ByteArrayResource
ResouceLoader
https://docs.spring.io/spring/docs/5.2.7.RELEASE/spring-framework-reference/core.html#resources-resourceloader
ResourceLoaderはリソースを取得するためのinstance
すべての appliation contextはresouceLoaderを実装している。そのため、application contextsはresouceを取得するために使えるかもしれない
application cotextは以下のprefixに対応している
classpath:
file:
http:
none
e.g. some/resource/path/myTemplate.txt
ClassPathXmlApplicationContextが入ってくるのでClassPathのものが読まれる