Internally, Spring uses another interface, ResourceLoader, and the default implementation,
DefaultResourceLoader, to locate and create Resource instances. However, you generally won't interact
with DefaultResourceLoader, instead using another ResourceLoader implementation--
ApplicationContext.
Listing 5-41 shows a sample application that accesses three resources using ApplicationContext.
Listing 5-41. Accessing Resources
package com.apress.prospring3.ch5.resource;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.core.io.Resource;
public class ResourceDemo {
public static void main(String[] args) throws Exception{
ApplicationContext ctx = new ClassPathXmlApplicationContext(
"classpath:events/events.xml");
Resource res1 = ctx.getResource("file:///d:/temp/test.txt");
displayInfo(res1);
Resource res2 = ctx.getResource("classpath:test.txt");
displayInfo(res2);
Resource res3 = ctx.getResource("http://www.google.co.uk");
displayInfo(res3);
}
private static void displayInfo(Resource res) throws Exception{
System.out.println(res.getClass());
System.out.println(res.getURL().getContent());
System.out.println("");
}
}
You should note that the configuration file used in this example is unimportant. Notice that in each
call to getResource() we pass in a URI for each resource. You will recognize the common file: and
http: protocols that we pass in for res1 and res3. The classpath: protocol we use for res2 is Spring-
specific and indicates that the ResourceLoader should look in the classpath for the resource. Running this
example results in the following output:
class org.springframework.core.io.UrlResource
sun.net.www.content.text.PlainTextInputStream@709446e4
class org.springframework.core.io.ClassPathResource
sun.net.www.content.text.PlainTextInputStream@16ba5c7a
class org.springframework.core.io.UrlResource
sun.net.www.protocol.http.HttpURLConnection$HttpInputStream@6825c828
Notice that for both the file: and http: protocols, Spring returns a UrlResource instance. Spring
does include a FileSystemResource class, but the DefaultResourceLoader does not use this class at all. It's
because Spring's default resource-loading strategy treats the URL and file as the same type of resource
with difference protocols (i.e., file: and http:). If an instance of FileSystemResource is required, use the
FileSystemResourceLoader. Once a Resource instance is obtained, you are free to access the contents as
Search WWH :
Custom Search
Previous Page
Spring Framework 3 Topic Index
Next Page
Spring Framework 3 Bookmarks
Home