Resource Management
Applications constantly read files: templates, SQL migrations, certificates, JSON fixtures, and message bundles.
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
ApplicationContextbacked by the classpath treats it as a classpath path. - Every
ApplicationContextis aResourceLoader(ctx.getResource(...)) and aResourcePatternResolver(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()orgetContentAsString(), nevergetFile(), which throws for resources inside a JAR. - Sort the results of pattern scans explicitly — the order returned by
getResourcesis 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:
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();}}@Configurationclass AppConfig {@BeanWelcomeTemplate 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
Resourcewith@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 — useclasspath*:. - 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.
1IntermediateQuestionWhat is the difference between classpath: and classpath*:?+
Answer
2IntermediateQuestionWhy can Resource.getFile() fail in production but work locally?+
Answer
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.