Classpath and Resource Loading
What is the Classpath?
Classpath is the list of locations (folders or JARs) where the Java Virtual Machine (JVM) and Spring Framework search for class files and resources (like .properties
, .yml
, .xml
, etc.).
It includes:
/src/main/java
→ compiled into/target/classes
/src/main/resources
→ also copied to/target/classes
Dependencies → JARs included via Maven/Gradle
Everything inside /target/classes
and JARs in your dependencies becomes part of the runtime classpath.
Why Classpath Matters in Spring ?
Spring uses the classpath to:
Load configuration files (
application.properties
, YAML, XML)Locate and register beans via classpath scanning
Perform conditional configurations (via
@ConditionalOnClass
)Load static resources, templates, and files
Handle features like internationalization (loading
.properties
)
src/main/resources
and the Classpath
src/main/resources
and the ClasspathEverything inside the src/main/resources
directory is automatically copied into target/classes
during the build.
At runtime, the target/classes
directory is part of the classpath. So when we place something like application.properties
in src/main/resources
, Spring can load it using:
No extra configuration needed — it’s just part of the classpath.
How Classpath Impacts Spring Features ?
a. @ComponentScan
Spring uses classpath scanning to automatically discover and register beans with annotations like @Component
, @Service
, etc.
b. @ConditionalOnClass
Used in Spring Boot’s auto-configuration to conditionally create beans if a class is present on the classpath.
c. spring.factories / spring.autocOnfiguration.imports
Auto-configuration is triggered based on the presence of classes on the classpath.
How Spring Loads Resources from the Classpath ?
Spring abstracts away resource loading using the org.springframework.core.io.Resource
interface. We don’t have to worry about where the resource is stored — Spring handles it based on the given prefix.
Using ResourceLoader
ResourceLoader
Using @Value
@Value
Using ClassPathResource
Directly
ClassPathResource
DirectlyCommon Classpath Prefixes
classpath:
Load a single resource from the root of the classpath.
classpath*:
Load multiple resources matching a pattern (used for scanning JARs too).
Resource Loading Example
Assume a file exists at:
We can load it using:
Last updated
Was this helpful?