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:

Java
Resource template = ctx.getResource("some/resource/path/myTemplate.txt");
Kotlin
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:

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

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

Java
Resource template = ctx.getResource("file:///some/resource/path/myTemplate.txt");
Kotlin
val template = ctx.getResource("file:///some/resource/path/myTemplate.txt")
Java
Resource template = ctx.getResource("https://myhost.com/resource/path/myTemplate.txt");
Kotlin
val template = ctx.getResource("https://myhost.com/resource/path/myTemplate.txt")

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

Table 10. Resource lines
Prefix Example Explanation

classpath:

classpath:com/myapp/config.xml

Loads from the classpath.

file:

file:///data/config.xml

Loads as URL from the file system.

https:

https://myserver/logo.png

Loads as URL.

(none)

/data/config.xml

Depends on the underlying interface ApplicationContext.