Mastering Java Resource Loading: Class vs ClassLoader and Spring Tips
This article explains how to correctly load resources in Java using Class and ClassLoader getResource methods, compares their behavior, demonstrates batch resource retrieval, and shows how Spring's ResourceLoader and ResourcePatternResolver simplify resource access, providing practical code examples and best‑practice guidelines.
Ways to Access Resources
In Java, resources can be accessed via:
Class.getResource
ClassLoader.getResource
ClassLoader.getResources (for multiple resources)
ClassLoader.getSystemResource (static method)
Class can be obtained via ClassName.class or instance.getClass(). ClassLoader can be obtained in several ways:
Calling Class.getClassLoader(), e.g., getClass().getClassLoader() Using the current thread: Thread.currentThread().getContextClassLoader() Getting the system loader:
ClassLoader.getSystemClassLoader()Difference between Class.getResource and ClassLoader.getResource
public class ClassLoaderAndClassContrast {
public static void main(String[] args) throws Exception {
Class<ClassLoaderAndClassContrast> aClass = ClassLoaderAndClassContrast.class;
ClassLoader classLoader = aClass.getClassLoader();
URL resource = classLoader.getResource("cookies.properties");
URL resource1 = aClass.getResource("dir/cookies.properties");
if (resource != null) {
byte[] bytes = FileCopyUtils.copyToByteArray(resource.openStream());
System.out.println(new String(bytes));
}
}
}The main difference is the starting point for resource lookup.
ClassLoader ignores the current class's package and always uses the classpath as the base; when using ClassLoader, the path must not start with "/", otherwise null is returned.
Class.getResource treats a leading "/" as an absolute path relative to the classpath; without a leading "/", the path is relative to the class’s package.
In practice, prefer Class.getResource, but use ClassLoader.getResources when you need to load multiple resources.
public class ClassLoaderAndClassContrast {
Class<ClassLoaderAndClassContrast> cls = ClassLoaderAndClassContrast.class;
ClassLoader ldr = cls.getClassLoader();
public static void println(Object s) {
System.out.println(s);
}
void showResource(String name) {
println("## Test resource for: " + name + " ##");
println(String.format("ClassLoader#getResource(\"%s\")=%s", name, ldr.getResource(name)));
println(String.format("Class#getResource(\"%s\")=%s", name, cls.getResource(name)));
}
public final void testForResource() throws Exception {
showResource("");
showResource("/");
showResource(cls.getSimpleName() + ".class");
String n = cls.getName().replace('.', '/') + ".class";
showResource(n);
showResource("/" + n);
showResource("java/lang/Object.class");
showResource("/java/lang/Object.class");
}
public static void main(String[] args) throws Exception {
println("java.class.path: " + System.getProperty("java.class.path"));
println("user.dir: " + System.getProperty("user.dir"));
println("");
ClassLoaderAndClassContrast t = new ClassLoaderAndClassContrast();
t.testForResource();
}
}Batch Resource Retrieval
ClassLoader.getResources can obtain multiple resources.
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
Enumeration<URL> resources = classLoader.getResources("META-INF/MANIFEST.MF");Spring ResourceLoader
Spring provides ResourceLoader and ResourcePatternResolver interfaces to simplify resource access; ResourceUtils offers utility methods for resource type checks.
// All three examples load the same resource; the path must start from the classpath base.
ClassPathXmlApplicationContext applicationContext1 = new ClassPathXmlApplicationContext("beans.spring.xml");
ClassPathXmlApplicationContext applicationContext2 = new ClassPathXmlApplicationContext("/beans.spring.xml");
ClassPathXmlApplicationContext applicationContext3 = new ClassPathXmlApplicationContext("classpath:/beans.spring.xml");
// To match multiple resources, use classpath*: with a wildcard.
ClassPathXmlApplicationContext applicationContext4 = new ClassPathXmlApplicationContext("classpath*:/**/beans.spring.xml");ResourceLoader interface
ResourcePatternResolver interface – key
Example using ResourcePatternResolver:
String txt = "";
ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
Resource[] resources = resolver.getResources("templates/layout/email.html");
Resource resource = resources[0];
// Obtain an InputStream because files inside a JAR cannot be accessed via a plain file path.
InputStream stream = resource.getInputStream();
StringBuilder buffer = new StringBuilder();
byte[] bytes = new byte[1024];
try {
for (int n; (n = stream.read(bytes)) != -1; ) {
buffer.append(new String(bytes, 0, n));
}
} catch (IOException e) {
e.printStackTrace();
}
txt = buffer.toString();These snippets demonstrate correct usage of getResource methods and Spring’s resource‑loading utilities.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Java Interview Crash Guide
Dedicated to sharing Java interview Q&A; follow and reply "java" to receive a free premium Java interview guide.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
