The ResourceLoader interface is intended to be implemented by objects that can return (that is, load) Resource instances. The following listing shows the definition of the ResourceLoader interface:

public interface ResourceLoader {
    Resource getResource(String location);
    ClassLoader getClassLoader();

All application contexts implement the ResourceLoader interface. Therefore, all application contexts can be used to obtain Resource instances.

If you call getResource() on a specific application context, and the specified location path does not have a specific prefix, you will get back the Resource type corresponding to that specific application context. For example, suppose the following code snippet was run against a ClassPathXmlApplicationContext instance:

Resource template = ctx.getResource("some/resource/path/myTemplate.txt");
val template = ctx.getResource("some/resource/path/myTemplate.txt")

For ClassPathXmlApplicationContext this code returns ClassPathResource. If the same method were run on a FileSystemXmlApplicationContext instance, it would return a FileSystemResource. For WebApplicationContext it returns a ServletContextResource. Likewise, it will return the appropriate objects for each context.

As a result, it becomes possible to load resources according to a specific application context.

On the other hand, you can also force the use of ClassPathResource regardless of the application context type by specifying a special prefix classpath:, as shown in the following example:

Resource template = ctx.getResource("classpath:some/resource/path/myTemplate.txt");
val template = ctx.getResource("classpath:some/resource/path/myTemplate.txt")

Similarly, you can force the use of UrlResource by specifying any of the standard prefixes. The following examples use the file and https prefixes:

Resource template = ctx.getResource("file:///some/resource/path/myTemplate.txt");
val template = ctx.getResource("file:///some/resource/path/myTemplate.txt")
Resource template = ctx.getResource("");
val template = ctx.getResource("")

The following table briefly describes the strategy for converting String objects to Resource objects:

Table 10. Resource lines
Prefix Example Explanation



Loads from the classpath.



Loads as URL from the file system.



Loads as URL.



Depends on the underlying interface ApplicationContext.