Spring爲資源管理提供了一個Resource接口,並提供了幾個Resource的實現。它們都需要一個String表示的資源的實際位置。依據這個String,Spring將會自動爲你選擇正確的Resource實現。
下面一段代碼,我爲了得到一個資源的位置,定義了個屬性,一個是file代表文件的路徑(相對或絕對),一個是Resouce接口的屬性。在Spring的任何Context中都可以通過設置Resource的屬性來得到資源的位置。
private String file;
private Resource resource;
public void setResource(Resource resource) {
this.resource = resource;
try {
this.file = resource.getFile().getAbsolutePath();
} catch (IOException e) {
e.printStackTrace();
throw new RuntimeException(e.getMessage());
}
}
public void setFile(String file) {
this.file = file;
}
Spring配置文件如下:
<bean id="mybean" class="net.jf.mybean">
<property name="resource">
<value>/WEB-INF/config.xml</value>
</property>
</bean>
上面的例子是在WebApplicationAContext中的。Spring會根據Context的運行環境決定去哪裏加載資源。如果是Application程序。即使用類似ClassPathXmlApplicationContext這樣的Context,Spring則會使用ClassPathSource來代表資源。將會在程序運行時的ClassPath中尋找資源。但要注意一點。Spring目前能找到的資源是在FileSystem中的。而不能找到Jar包裏面的資源,就算你的資源的確在ClassPath當中。這一點在JavaDoc裏有說明。我又是在犯是同樣的錯誤後纔想到去查找文檔。。。嘿。教訓啊。
這些只是很粗淺的用法。記下來以備忘 。。如果有不正確或不妥當的地方還望指正。:)