Spring Framework Tutorial 0/19 lessons ~6 min read Lesson 10

    Resource Management

    Applications constantly read files: templates, SQL migrations, certificates, JSON fixtures, and message bundles.

    Course progress0%
    Focus
    10 guided sections
    Practice signal
    Examples included
    Career prep
    Interview Q&A included

    Introduction

    Applications constantly read files: templates, SQL migrations, certificates, JSON fixtures, and message bundles. Spring's Resource abstraction gives you one API for all of them, whether the file lives on the classpath, the file system, a URL, or inside a JAR.

    The same abstraction powers @PropertySource, Spring's SQL script runners, and Boot's configuration loading, so understanding it explains a lot of "file not found" incidents.

    Purpose of this lesson

    You will load resources by prefix, inject them with @Value, scan for many files with wildcard patterns, and avoid the classic JAR-packaging mistakes.

    Understanding the topic

    Resource prefixes:

    • classpath:templates/welcome.txt — first match on the classpath (works inside JARs).
    • classpath*:db/migration/*.sql — all matches across every JAR and directory on the classpath.
    • file:/etc/app/config.json — a file-system path.
    • https://example.com/rules.json — a URL resource.
    • No prefix — depends on the context: an ApplicationContext backed by the classpath treats it as a classpath path.
    • Every ApplicationContext is a ResourceLoader (ctx.getResource(...)) and a ResourcePatternResolver (ctx.getResources(...)).

    Key Resource methods: exists(), getFilename(), contentLength(), getInputStream(), and, since Spring 6.0, getContentAsString(Charset).

    Production implementation

    Production rules for resources:

    • Inside a JAR, a classpath resource has no real file. Use getInputStream() or getContentAsString(), never getFile(), which throws for resources inside a JAR.
    • Sort the results of pattern scans explicitly — the order returned by getResources is not guaranteed.
    • Keep secrets (keys, certificates) outside the JAR and load them with file: from a mounted volume or secret store.
    • Treat URL resources as network calls: they can be slow or fail, so do not load them on a hot request path.

    Informative example

    Injecting, checking, and scanning resources — the classpath contains templates/welcome.txt (Welcome to TechLearningPRO, {name}!) and two migration files:

    java
    public class WelcomeTemplate {
    private final Resource template;
    public WelcomeTemplate(@Value("classpath:templates/welcome.txt") Resource template) {
    this.template = template;
    }
    public String render(String name) throws IOException {
    return template.getContentAsString(StandardCharsets.UTF_8).replace("{name}", name).strip();
    }
    }
    @Configuration
    class AppConfig {
    @Bean
    WelcomeTemplate welcomeTemplate(@Value("classpath:templates/welcome.txt") Resource r) {
    return new WelcomeTemplate(r);
    }
    }
    public static void main(String[] args) throws IOException {
    try (var ctx = new AnnotationConfigApplicationContext(AppConfig.class)) {
    System.out.println(ctx.getBean(WelcomeTemplate.class).render("Asha"));
    Resource missing = ctx.getResource("classpath:templates/missing.txt");
    System.out.println("missing exists? " + missing.exists());
    var resolver = new PathMatchingResourcePatternResolver();
    Resource[] migrations = resolver.getResources("classpath*:db/migration/V*.sql");
    Arrays.sort(migrations, Comparator.comparing(Resource::getFilename));
    for (Resource m : migrations) {
    System.out.println(m.getFilename() + " (" + m.contentLength() + " bytes)");
    }
    }
    }

    Output

    Welcome to TechLearningPRO, Asha!
    missing exists? false
    V1__create_orders.sql (50 bytes)
    V2__add_status.sql (50 bytes)

    ctx.getResource never throws for a missing file — it returns a handle whose exists() is false. Reading from that handle is what throws, so check exists() for optional files.

    Best practices

    • Inject a Resource with @Value("classpath:…") instead of passing path strings around.
    • Validate required resources at startup and fail fast with a clear message.
    • Read text with an explicit charset (StandardCharsets.UTF_8).

    Common mistakes

    • Calling resource.getFile() — it works in the IDE (exploded classes) and fails in the packaged JAR.
    • Using classpath: with a wildcard and expecting results from other JARs — use classpath*:.
    • Assuming a stable scan order and applying migrations out of sequence.
    • Reading the same large resource on every request instead of once at startup.

    Advanced interview questions

    Interview Prep

    Practice concise answers, then expand each card for the explanation.

    2 questions
    1IntermediateQuestionWhat is the difference between classpath: and classpath*:?+

    Answer

    classpath: returns the first matching resource found on the classpath. classpath*: returns every match across all classpath roots, which is needed to collect files with the same path from multiple JARs, such as migration scripts or plugin descriptors.
    2IntermediateQuestionWhy can Resource.getFile() fail in production but work locally?+

    Answer

    Locally, classes and resources are often exploded on disk, so a real file exists. In a packaged JAR the resource is a JAR entry with no file-system path, so getFile() throws. Use getInputStream() or getContentAsString() instead.

    Hands-on exercise

    Hands-on: add db/migration/V3__add_index.sql and confirm the scan now prints three files in version order. Then package the app as a JAR, run it with java -jar, and prove that getContentAsString works while a call to getFile() throws a FileNotFoundException.

    Summary

    Resource gives one API for classpath, file, and URL content. Inject resources, read them as streams, scan with classpath*: when files come from several JARs, and sort scan results yourself.

    Ready to mark this lesson complete?Track your journey across the entire course.