Spring’s Resource
interface is meant to be a more capable interface for abstracting access to low-level resources。
public interface Resource extends InputStreamSource { boolean exists(); boolean isOpen(); URL getURL() throws IOException; File getFile() throws IOException; Resource createRelative(String relativePath) throws IOException; String getFilename(); String getDescription(); }
spring build-in resources
- UrlResource
- ClassPathResource
- FileSystemResource
- ServletContextResource
- InputStreamResource
- ByteArrayResource
spring怎样加载这些资源
public interface ResourceLoader { Resource getResource(String location); }
所有的spring context都实现了这个接口,所以可以使用spring的context加载这些资源。
例如:
Resource template = ctx.getResource("some/resource/path/myTemplate.txt");
那么,ctx获取的是哪一种类型的资源呢,是UrlResources,还是ClassPathResource。。。
这取决于ctx的类型,如果ctx是ClassPathXmlApplicationContext,则获取的是classPathResource.如果ctx是FileSystemXmlApplicationContext则获取的是FileSystemResouces.。。。
另一方面,你也可以强制spring以某种资源开式来获取:
Resource template = ctx.getResource("classpath:some/resource/path/myTemplate.txt");
则,不管ctx是什么类型,都会以ClassPathResource的形式来获取。
其它形式还有:
Prefix | Example | Explanation |
---|---|---|
classpath: |
| Loaded from the classpath. |
file: | Loaded as a | |
http: | Loaded as a | |
(none) |
| Depends on the underlying |
那么怎样在代码中获取Resource呢
实现接口的方式:
public interface ResourceLoaderAware { void setResourceLoader(ResourceLoader resourceLoader); }在spring管理的bean中实现该接口,即可获取Resources;
以注解的方式
要spring2.5以后,以
@autowired
Resouces resouces;
的方式即可注入。
方式三
又由于所有的context都实现了ResourceLoader接口,所以实现ApplicationContextAware接口也可以获取Resources。
获取Resource后,怎样注入该Resouces
class MyBean{
<span style="white-space:pre"> </span> Resouces template;
}
<bean id="myBean" class="..."> <property name="template" value="some/resource/path/myTemplate.txt"/> </bean>
以value=“资源路径” 的方式即可注入。spring中有个特殊的bean PropertyEditor会将相应的路径转换成Resouces。
资源路径还可以加入资源前缀。如:
<property name="template" value="classpath:some/resource/path/myTemplate.txt">
<property name="template" value="file:///some/resource/path/myTemplate.txt"/>
那么怎样加载jar中的资源呢。
ApplicationContext ctx = new ClassPathXmlApplicationContext("classpath*:conf/appContext.xml");以classpath*为前缀,则会加载所有jar中的conf/appContext.xml文件。在以Componet形式开的的工程中将非常有效。