This chapter covers how Spring handles resources and how you can work with resources in Spring. It includes the following topics:

Introduction

The resource interface, built-in resource implementations, the resourceloader interface, the resourcepatternresolver interface, the resourceloaderaware interface, resources as dependencies, application contexts and resource paths.

Java’s standard java.net.URL class and standard handlers for various URL prefixes, unfortunately, are not quite adequate enough for all access to low-level resources. For example, there is no standardized URL implementation that may be used to access a resource that needs to be obtained from the classpath or relative to a ServletContext . While it is possible to register new handlers for specialized URL prefixes (similar to existing handlers for prefixes such as http: ), this is generally quite complicated, and the URL interface still lacks some desirable functionality, such as a method to check for the existence of the resource being pointed to.

Spring’s Resource interface located in the org.springframework.core.io. package is meant to be a more capable interface for abstracting access to low-level resources. The following listing provides an overview of the Resource interface. See the Resource javadoc for further details.

As the definition of the Resource interface shows, it extends the InputStreamSource interface. The following listing shows the definition of the InputStreamSource interface:

Some of the most important methods from the Resource interface are:

getInputStream() : Locates and opens the resource, returning an InputStream for reading from the resource. It is expected that each invocation returns a fresh InputStream . It is the responsibility of the caller to close the stream.

exists() : Returns a boolean indicating whether this resource actually exists in physical form.

isOpen() : Returns a boolean indicating whether this resource represents a handle with an open stream. If true , the InputStream cannot be read multiple times and must be read once only and then closed to avoid resource leaks. Returns false for all usual resource implementations, with the exception of InputStreamResource .

getDescription() : Returns a description for this resource, to be used for error output when working with the resource. This is often the fully qualified file name or the actual URL of the resource.

Other methods let you obtain an actual URL or File object representing the resource (if the underlying implementation is compatible and supports that functionality).

Some implementations of the Resource interface also implement the extended WritableResource interface for a resource that supports writing to it.

Spring itself uses the Resource abstraction extensively, as an argument type in many method signatures when a resource is needed. Other methods in some Spring APIs (such as the constructors to various ApplicationContext implementations) take a String which in unadorned or simple form is used to create a Resource appropriate to that context implementation or, via special prefixes on the String path, let the caller specify that a specific Resource implementation must be created and used.

While the Resource interface is used a lot with Spring and by Spring, it is actually very convenient to use as a general utility class by itself in your own code, for access to resources, even when your code does not know or care about any other parts of Spring. While this couples your code to Spring, it really only couples it to this small set of utility classes, which serves as a more capable replacement for URL and can be considered equivalent to any other library you would use for this purpose.

The abstraction does not replace functionality. It wraps it where possible. For example, a wraps a URL and uses the wrapped to do its work.

Spring includes several built-in Resource implementations:

UrlResource

Classpathresource, filesystemresource, pathresource, servletcontextresource, inputstreamresource, bytearrayresource.

For a complete list of Resource implementations available in Spring, consult the "All Known Implementing Classes" section of the Resource javadoc.

UrlResource wraps a java.net.URL and can be used to access any object that is normally accessible with a URL, such as files, an HTTPS target, an FTP target, and others. All URLs have a standardized String representation, such that appropriate standardized prefixes are used to indicate one URL type from another. This includes file: for accessing filesystem paths, https: for accessing resources through the HTTPS protocol, ftp: for accessing resources through FTP, and others.

A UrlResource is created by Java code by explicitly using the UrlResource constructor but is often created implicitly when you call an API method that takes a String argument meant to represent a path. For the latter case, a JavaBeans PropertyEditor ultimately decides which type of Resource to create. If the path string contains a well-known (to property editor, that is) prefix (such as classpath: ), it creates an appropriate specialized Resource for that prefix. However, if it does not recognize the prefix, it assumes the string is a standard URL string and creates a UrlResource .

This class represents a resource that should be obtained from the classpath. It uses either the thread context class loader, a given class loader, or a given class for loading resources.

This Resource implementation supports resolution as a java.io.File if the class path resource resides in the file system but not for classpath resources that reside in a jar and have not been expanded (by the servlet engine or whatever the environment is) to the filesystem. To address this, the various Resource implementations always support resolution as a java.net.URL .

A ClassPathResource is created by Java code by explicitly using the ClassPathResource constructor but is often created implicitly when you call an API method that takes a String argument meant to represent a path. For the latter case, a JavaBeans PropertyEditor recognizes the special prefix, classpath: , on the string path and creates a ClassPathResource in that case.

This is a Resource implementation for java.io.File handles. It also supports java.nio.file.Path handles, applying Spring’s standard String-based path transformations but performing all operations via the java.nio.file.Files API. For pure java.nio.path.Path based support use a PathResource instead. FileSystemResource supports resolution as a File and as a URL .

This is a Resource implementation for java.nio.file.Path handles, performing all operations and transformations via the Path API. It supports resolution as a File and as a URL and also implements the extended WritableResource interface. PathResource is effectively a pure java.nio.path.Path based alternative to FileSystemResource with different createRelative behavior.

This is a Resource implementation for ServletContext resources that interprets relative paths within the relevant web application’s root directory.

It always supports stream access and URL access but allows java.io.File access only when the web application archive is expanded and the resource is physically on the filesystem. Whether or not it is expanded and on the filesystem or accessed directly from the JAR or somewhere else like a database (which is conceivable) is actually dependent on the Servlet container.

An InputStreamResource is a Resource implementation for a given InputStream . It should be used only if no specific Resource implementation is applicable. In particular, prefer ByteArrayResource or any of the file-based Resource implementations where possible.

In contrast to other Resource implementations, this is a descriptor for an already-opened resource. Therefore, it returns true from isOpen() . Do not use it if you need to keep the resource descriptor somewhere or if you need to read a stream multiple times.

This is a Resource implementation for a given byte array. It creates a ByteArrayInputStream for the given byte array.

It is useful for loading content from any given byte array without having to resort to a single-use InputStreamResource .

The ResourceLoader interface is meant to be implemented by objects that can return (that is, load) Resource instances. The following listing shows the ResourceLoader interface definition:

All application contexts implement the ResourceLoader interface. Therefore, all application contexts may be used to obtain Resource instances.

When you call getResource() on a specific application context, and the location path specified doesn’t have a specific prefix, you get back a Resource type that is appropriate to that particular application context. For example, assume the following snippet of code was run against a ClassPathXmlApplicationContext instance:

Against a ClassPathXmlApplicationContext , that code returns a ClassPathResource . If the same method were run against a FileSystemXmlApplicationContext instance, it would return a FileSystemResource . For a WebApplicationContext , it would return a ServletContextResource . It would similarly return appropriate objects for each context.

As a result, you can load resources in a fashion appropriate to the particular application context.

On the other hand, you may also force ClassPathResource to be used, regardless of the application context type, by specifying the special classpath: prefix, as the following example shows:

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

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

Table 1. Resource strings
Prefix Example Explanation

classpath:

Loaded from the classpath.

file:

Loaded as a from the filesystem. See also Caveats.

https:

Loaded as a .

(none)

Depends on the underlying .

The ResourcePatternResolver interface is an extension to the ResourceLoader interface which defines a strategy for resolving a location pattern (for example, an Ant-style path pattern) into Resource objects.

As can be seen above, this interface also defines a special classpath*: resource prefix for all matching resources from the class path. Note that the resource location is expected to be a path without placeholders in this case — for example, classpath*:/config/beans.xml . JAR files or different directories in the class path can contain multiple files with the same path and the same name. See Wildcards in Application Context Constructor Resource Paths and its subsections for further details on wildcard support with the classpath*: resource prefix.

A passed-in ResourceLoader (for example, one supplied via ResourceLoaderAware semantics) can be checked whether it implements this extended interface too.

PathMatchingResourcePatternResolver is a standalone implementation that is usable outside an ApplicationContext and is also used by ResourceArrayPropertyEditor for populating Resource[] bean properties. PathMatchingResourcePatternResolver is able to resolve a specified resource location path into one or more matching Resource objects. The source path may be a simple path which has a one-to-one mapping to a target Resource , or alternatively may contain the special classpath*: prefix and/or internal Ant-style regular expressions (matched using Spring’s org.springframework.util.AntPathMatcher utility). Both of the latter are effectively wildcards.

in any standard is in fact an instance of which implements the interface. The same is true for the instance itself which also implements the interface and delegates to the default .

The ResourceLoaderAware interface is a special callback interface which identifies components that expect to be provided a ResourceLoader reference. The following listing shows the definition of the ResourceLoaderAware interface:

When a class implements ResourceLoaderAware and is deployed into an application context (as a Spring-managed bean), it is recognized as ResourceLoaderAware by the application context. The application context then invokes setResourceLoader(ResourceLoader) , supplying itself as the argument (remember, all application contexts in Spring implement the ResourceLoader interface).

Since an ApplicationContext is a ResourceLoader , the bean could also implement the ApplicationContextAware interface and use the supplied application context directly to load resources. However, in general, it is better to use the specialized ResourceLoader interface if that is all you need. The code would be coupled only to the resource loading interface (which can be considered a utility interface) and not to the whole Spring ApplicationContext interface.

In application components, you may also rely upon autowiring of the ResourceLoader as an alternative to implementing the ResourceLoaderAware interface. The traditional constructor and byType autowiring modes (as described in Autowiring Collaborators ) are capable of providing a ResourceLoader for either a constructor argument or a setter method parameter, respectively. For more flexibility (including the ability to autowire fields and multiple parameter methods), consider using the annotation-based autowiring features. In that case, the ResourceLoader is autowired into a field, constructor argument, or method parameter that expects the ResourceLoader type as long as the field, constructor, or method in question carries the @Autowired annotation. For more information, see Using @Autowired .

To load one or more objects for a resource path that contains wildcards or makes use of the special resource prefix, consider having an instance of autowired into your application components instead of .

If the bean itself is going to determine and supply the resource path through some sort of dynamic process, it probably makes sense for the bean to use the ResourceLoader or ResourcePatternResolver interface to load resources. For example, consider the loading of a template of some sort, where the specific resource that is needed depends on the role of the user. If the resources are static, it makes sense to eliminate the use of the ResourceLoader interface (or ResourcePatternResolver interface) completely, have the bean expose the Resource properties it needs, and expect them to be injected into it.

What makes it trivial to then inject these properties is that all application contexts register and use a special JavaBeans PropertyEditor , which can convert String paths to Resource objects. For example, the following MyBean class has a template property of type Resource .

In an XML configuration file, the template property can be configured with a simple string for that resource, as the following example shows:

Note that the resource path has no prefix. Consequently, because the application context itself is going to be used as the ResourceLoader , the resource is loaded through a ClassPathResource , a FileSystemResource , or a ServletContextResource , depending on the exact type of the application context.

If you need to force a specific Resource type to be used, you can use a prefix. The following two examples show how to force a ClassPathResource and a UrlResource (the latter being used to access a file in the filesystem):

If the MyBean class is refactored for use with annotation-driven configuration, the path to myTemplate.txt can be stored under a key named template.path  — for example, in a properties file made available to the Spring Environment (see Environment Abstraction ). The template path can then be referenced via the @Value annotation using a property placeholder (see Using @Value ). Spring will retrieve the value of the template path as a string, and a special PropertyEditor will convert the string to a Resource object to be injected into the MyBean constructor. The following example demonstrates how to achieve this.

If we want to support multiple templates discovered under the same path in multiple locations in the classpath — for example, in multiple jars in the classpath — we can use the special classpath*: prefix and wildcarding to define a templates.path key as classpath*:/config/templates/*.txt . If we redefine the MyBean class as follows, Spring will convert the template path pattern into an array of Resource objects that can be injected into the MyBean constructor.

This section covers how to create application contexts with resources, including shortcuts that work with XML, how to use wildcards, and other details.

Constructing Application Contexts

An application context constructor (for a specific application context type) generally takes a string or array of strings as the location paths of the resources, such as XML files that make up the definition of the context.

When such a location path does not have a prefix, the specific Resource type built from that path and used to load the bean definitions depends on and is appropriate to the specific application context. For example, consider the following example, which creates a ClassPathXmlApplicationContext :

The bean definitions are loaded from the classpath, because a ClassPathResource is used. However, consider the following example, which creates a FileSystemXmlApplicationContext :

Now the bean definitions are loaded from a filesystem location (in this case, relative to the current working directory).

Note that the use of the special classpath prefix or a standard URL prefix on the location path overrides the default type of Resource created to load the bean definitions. Consider the following example:

Using FileSystemXmlApplicationContext loads the bean definitions from the classpath. However, it is still a FileSystemXmlApplicationContext . If it is subsequently used as a ResourceLoader , any unprefixed paths are still treated as filesystem paths.

Constructing ClassPathXmlApplicationContext Instances — Shortcuts

The ClassPathXmlApplicationContext exposes a number of constructors to enable convenient instantiation. The basic idea is that you can supply merely a string array that contains only the filenames of the XML files themselves (without the leading path information) and also supply a Class . The ClassPathXmlApplicationContext then derives the path information from the supplied class.

Consider the following directory layout:

The following example shows how a ClassPathXmlApplicationContext instance composed of the beans defined in files named services.xml and repositories.xml (which are on the classpath) can be instantiated:

See the ClassPathXmlApplicationContext javadoc for details on the various constructors.

Wildcards in Application Context Constructor Resource Paths

The resource paths in application context constructor values may be simple paths (as shown earlier), each of which has a one-to-one mapping to a target Resource or, alternately, may contain the special classpath*: prefix or internal Ant-style patterns (matched by using Spring’s PathMatcher utility). Both of the latter are effectively wildcards.

One use for this mechanism is when you need to do component-style application assembly. All components can publish context definition fragments to a well-known location path, and, when the final application context is created using the same path prefixed with classpath*: , all component fragments are automatically picked up.

Note that this wildcarding is specific to the use of resource paths in application context constructors (or when you use the PathMatcher utility class hierarchy directly) and is resolved at construction time. It has nothing to do with the Resource type itself. You cannot use the classpath*: prefix to construct an actual Resource , as a resource points to just one resource at a time.

Ant-style Patterns

Path locations can contain Ant-style patterns, as the following example shows:

When the path location contains an Ant-style pattern, the resolver follows a more complex procedure to try to resolve the wildcard. It produces a Resource for the path up to the last non-wildcard segment and obtains a URL from it. If this URL is not a jar: URL or container-specific variant (such as zip: in WebLogic, wsjar in WebSphere, and so on), a java.io.File is obtained from it and used to resolve the wildcard by traversing the filesystem. In the case of a jar URL, the resolver either gets a java.net.JarURLConnection from it or manually parses the jar URL and then traverses the contents of the jar file to resolve the wildcards.

Implications on Portability

If the specified path is already a file URL (either implicitly because the base ResourceLoader is a filesystem one or explicitly), wildcarding is guaranteed to work in a completely portable fashion.

If the specified path is a classpath location, the resolver must obtain the last non-wildcard path segment URL by making a Classloader.getResource() call. Since this is just a node of the path (not the file at the end), it is actually undefined (in the ClassLoader javadoc) exactly what sort of a URL is returned in this case. In practice, it is always a java.io.File representing the directory (where the classpath resource resolves to a filesystem location) or a jar URL of some sort (where the classpath resource resolves to a jar location). Still, there is a portability concern on this operation.

If a jar URL is obtained for the last non-wildcard segment, the resolver must be able to get a java.net.JarURLConnection from it or manually parse the jar URL, to be able to walk the contents of the jar and resolve the wildcard. This does work in most environments but fails in others, and we strongly recommend that the wildcard resolution of resources coming from jars be thoroughly tested in your specific environment before you rely on it.

The classpath*: Prefix

When constructing an XML-based application context, a location string may use the special classpath*: prefix, as the following example shows:

This special prefix specifies that all classpath resources that match the given name must be obtained (internally, this essentially happens through a call to ClassLoader.getResources(…​) ) and then merged to form the final application context definition.

The wildcard classpath relies on the method of the underlying . As most application servers nowadays supply their own implementation, the behavior might differ, especially when dealing with jar files. A simple test to check if works is to use the to load a file from within a jar on the classpath: . Try this test with files that have the same name but reside in two different locations — for example, files with the same name and same path but in different jars on the classpath. In case an inappropriate result is returned, check the application server documentation for settings that might affect the behavior.

You can also combine the classpath*: prefix with a PathMatcher pattern in the rest of the location path (for example, classpath*:META-INF/*-beans.xml ). In this case, the resolution strategy is fairly simple: A ClassLoader.getResources() call is used on the last non-wildcard path segment to get all the matching resources in the class loader hierarchy and then, off each resource, the same PathMatcher resolution strategy described earlier is used for the wildcard subpath.

Other Notes Relating to Wildcards

Note that classpath*: , when combined with Ant-style patterns, only works reliably with at least one root directory before the pattern starts, unless the actual target files reside in the file system. This means that a pattern such as classpath*:*.xml might not retrieve files from the root of jar files but rather only from the root of expanded directories.

Spring’s ability to retrieve classpath entries originates from the JDK’s ClassLoader.getResources() method, which only returns file system locations for an empty string (indicating potential roots to search). Spring evaluates URLClassLoader runtime configuration and the java.class.path manifest in jar files as well, but this is not guaranteed to lead to portable behavior.

switch of the JAR task. Also, classpath directories may not get exposed based on security policies in some environments — for example, stand-alone applications on JDK 1.7.0_45 and higher (which requires 'Trusted-Library' to be set up in your manifests. See ).

Ant-style patterns with classpath: resources are not guaranteed to find matching resources if the root package to search is available in multiple classpath locations. Consider the following example of a resource location:

Now consider an Ant-style path that someone might use to try to find that file:

Such a resource may exist in only one location in the classpath, but when a path such as the preceding example is used to try to resolve it, the resolver works off the (first) URL returned by getResource("com/mycompany"); . If this base package node exists in multiple ClassLoader locations, the desired resource may not exist in the first location found. Therefore, in such cases you should prefer using classpath*: with the same Ant-style pattern, which searches all classpath locations that contain the com.mycompany base package: classpath*:com/mycompany/**/service-context.xml .

FileSystemResource Caveats

A FileSystemResource that is not attached to a FileSystemApplicationContext (that is, when a FileSystemApplicationContext is not the actual ResourceLoader ) treats absolute and relative paths as you would expect. Relative paths are relative to the current working directory, while absolute paths are relative to the root of the filesystem.

For backwards compatibility (historical) reasons however, this changes when the FileSystemApplicationContext is the ResourceLoader . The FileSystemApplicationContext forces all attached FileSystemResource instances to treat all location paths as relative, whether they start with a leading slash or not. In practice, this means the following examples are equivalent:

The following examples are also equivalent (even though it would make sense for them to be different, as one case is relative and the other absolute):

In practice, if you need true absolute filesystem paths, you should avoid using absolute paths with FileSystemResource or FileSystemXmlApplicationContext and force the use of a UrlResource by using the file: URL prefix. The following examples show how to do so:

  • 6.2.0-SNAPSHOT
  • 6.1.12-SNAPSHOT
  • 6.1.11 current
  • 6.0.23-SNAPSHOT
  • Spring Boot
  • Spring Framework
  • Spring Cloud Build
  • Spring Cloud Bus
  • Spring Cloud Circuit Breaker
  • Spring Cloud Commons
  • Spring Cloud Config
  • Spring Cloud Consul
  • Spring Cloud Contract
  • Spring Cloud Function
  • Spring Cloud Gateway
  • Spring Cloud Kubernetes
  • Spring Cloud Netflix
  • Spring Cloud OpenFeign
  • Spring Cloud Stream
  • Spring Cloud Task
  • Spring Cloud Vault
  • Spring Cloud Zookeeper
  • Spring Data Cassandra
  • Spring Data Commons
  • Spring Data Couchbase
  • Spring Data Elasticsearch
  • Spring Data JPA
  • Spring Data KeyValue
  • Spring Data LDAP
  • Spring Data MongoDB
  • Spring Data Neo4j
  • Spring Data Redis
  • Spring Data JDBC & R2DBC
  • Spring Data REST
  • Spring Integration
  • Spring Batch
  • Spring Authorization Server
  • Spring LDAP
  • Spring Security Kerberos
  • Spring Session
  • Spring Vault
  • Spring AMQP
  • Spring GraphQL
  • Spring for Apache Kafka
  • Spring Modulith
  • Spring for Apache Pulsar
  • Spring Shell
  • All Docs...
  • Java Arrays
  • Java Strings
  • Java Collection
  • Java 8 Tutorial
  • Java Multithreading
  • Java Exception Handling
  • Java Programs
  • Java Project
  • Java Collections Interview
  • Java Interview Questions
  • Spring Boot
  • Spring Tutorial

Basics of Spring Framework

  • Introduction to Spring Framework
  • Spring Framework Architecture
  • 10 Reasons to Use Spring Framework in Projects
  • Spring Initializr
  • Difference Between Spring DAO vs Spring ORM vs Spring JDBC
  • Top 10 Most Common Spring Framework Mistakes
  • Spring vs. Struts in Java

Software Setup and Configuration

  • How to Download and Install Spring Tool Suite (Spring Tools 4 for Eclipse) IDE?
  • How to Create and Setup Spring Boot Project in Spring Tool Suite?
  • How to Create a Spring Boot Project with IntelliJ IDEA?
  • How to Create and Setup Spring Boot Project in Eclipse IDE?
  • How to Create a Dynamic Web Project in Eclipse/Spring Tool Suite?
  • How to Run Your First Spring Boot Application in IntelliJ IDEA?
  • How to Run Your First Spring Boot Application in Spring Tool Suite?
  • How to Turn on Code Suggestion in Eclipse or Spring Tool Suite?

Core Spring

  • Spring - Understanding Inversion of Control with Example
  • Spring - BeanFactory
  • Spring - ApplicationContext
  • Spring - Difference Between BeanFactory and ApplicationContext
  • Spring Dependency Injection with Example
  • Spring - Difference Between Inversion of Control and Dependency Injection
  • Spring - Injecting Objects By Constructor Injection
  • Spring - Setter Injection with Map
  • Spring - Dependency Injection with Factory Method
  • Spring - Dependency Injection by Setter Method
  • Spring - Setter Injection with Non-String Map
  • Spring - Constructor Injection with Non-String Map
  • Spring - Constructor Injection with Map
  • Spring - Setter Injection with Dependent Object
  • Spring - Constructor Injection with Dependent Object
  • Spring - Setter Injection with Collection
  • Spring - Setter Injection with Non-String Collection
  • Spring - Constructor Injection with Collection
  • Spring - Injecting Objects by Setter Injection
  • Spring - Injecting Literal Values By Setter Injection
  • Spring - Injecting Literal Values By Constructor Injection
  • Bean life cycle in Java Spring
  • Custom Bean Scope in Spring
  • How to Create a Spring Bean in 3 Different Ways?
  • Spring - IoC Container
  • Spring - Autowiring
  • Singleton and Prototype Bean Scopes in Java Spring
  • How to Configure Dispatcher Servlet in web.xml File?
  • Spring - Configure Dispatcher Servlet in Three Different Ways
  • How to Configure Dispatcher Servlet in Just Two Lines of Code in Spring?
  • Spring - When to Use Factory Design Pattern Instead of Dependency Injection
  • How to Create a Simple Spring Application?
  • Spring - init() and destroy() Methods with Example
  • Spring WebApplicationInitializer with Example
  • Spring - Project Modules
  • Spring - Remoting by HTTP Invoker
  • Spring - Expression Language(SpEL)
  • Spring - Variable in SpEL
  • What is Ambiguous Mapping in Spring?
  • Spring - Add New Query Parameters in GET Call Through Configurations
  • Spring - Integrate HornetQ
  • Remoting in Spring Framework
  • Spring - Application Events
  • Spring c-namespace with Example
  • Parse Nested User-Defined Functions using Spring Expression Language (SpEL)
  • Spring - AbstractRoutingDataSource
  • Circular Dependencies in Spring
  • Spring - ResourceLoaderAware with Example
  • Spring Framework Standalone Collections
  • How to Create a Project using Spring and Struts 2?
  • Spring - Perform Update Operation in CRUD
  • How to Transfer Data in Spring using DTO?
  • Spring - Resource Bundle Message Source (i18n)
  • Spring Application Without Any .xml Configuration
  • Spring - BeanPostProcessor
  • Spring and JAXB Integration
  • Spring - Difference Between Dependency Injection and Factory Pattern
  • Spring - REST Pagination
  • Spring - Remoting By Burlap
  • Spring - Remoting By Hessian
  • Spring with Castor Example
  • Spring - REST XML Response
  • Spring - Inheriting Bean
  • Spring - Change DispatcherServlet Context Configuration File Name
  • Spring - JMS Integration
  • Spring - Difference Between RowMapper and ResultSetExtractor
  • Spring with Xstream
  • Spring - RowMapper Interface with Example
  • Spring - util:constant
  • Spring - Static Factory Method
  • Spring - FactoryBean
  • Difference between EJB and Spring
  • Spring Framework Annotations
  • Spring Core Annotations
  • Spring - Stereotype Annotations
  • Spring @Bean Annotation with Example
  • Spring @Controller Annotation with Example
  • Spring @Value Annotation with Example
  • Spring @Configuration Annotation with Example
  • Spring @ComponentScan Annotation with Example
  • Spring @Qualifier Annotation with Example
  • Spring @Service Annotation with Example
  • Spring @Repository Annotation with Example
  • Spring - Required Annotation
  • Spring @Component Annotation with Example
  • Spring @Autowired Annotation
  • Spring - @PostConstruct and @PreDestroy Annotation with Example
  • Java Spring - Using @PropertySource Annotation and Resource Interface
  • Java Spring - Using @Scope Annotation to Set a POJO's Scope
  • Spring @Required Annotation with Example
  • Spring Boot Tutorial
  • Spring MVC Tutorial

Spring with REST API

  • Spring - REST JSON Response
  • Spring - REST Controller

Spring Data

  • What is Spring Data JPA?
  • Spring Data JPA - Find Records From MySQL
  • Spring Data JPA - Delete Records From MySQL
  • Spring Data JPA - @Table Annotation
  • Spring Data JPA - Insert Data in MySQL Table
  • Spring Data JPA - Attributes of @Column Annotation with Example
  • Spring Data JPA - @Column Annotation
  • Spring Data JPA - @Id Annotation
  • Introduction to the Spring Data Framework
  • Spring Boot | How to access database using Spring Data JPA
  • How to Make a Project Using Spring Boot, MySQL, Spring Data JPA, and Maven?

Spring JDBC

  • Spring - JDBC Template
  • Spring JDBC Example
  • Spring - SimpleJDBCTemplate with Example
  • Spring - Prepared Statement JDBC Template
  • Spring - NamedParameterJdbcTemplate
  • Spring - Using SQL Scripts with Spring JDBC + JPA + HSQLDB
  • Spring - ResultSetExtractor

Spring Hibernate

  • Spring Hibernate Configuration and Create a Table in Database
  • Hibernate Lifecycle
  • Java - JPA vs Hibernate
  • Spring ORM Example using Hibernate
  • Hibernate - One-to-One Mapping
  • Hibernate - Cache Eviction with Example
  • Hibernate - Cache Expiration
  • Hibernate - Enable and Implement First and Second Level Cache
  • Hibernate - Save Image and Other Types of Values to Database
  • Hibernate - Pagination
  • Hibernate - Different Cascade Types
  • Hibernate Native SQL Query with Example
  • Hibernate - Caching
  • Hibernate - @Embeddable and @Embedded Annotation
  • Hibernate - Eager/Lazy Loading
  • Hibernate - get() and load() Method
  • Hibernate Validator
  • CRUD Operations using Hibernate
  • Hibernate Example without IDE
  • Hibernate - Inheritance Mapping
  • Automatic Table Creation Using Hibernate
  • Hibernate - Batch Processing
  • Hibernate - Component Mapping
  • Hibernate - Mapping List
  • Hibernate - Collection Mapping
  • Hibernate - Bag Mapping
  • Hibernate - Difference Between List and Bag Mapping
  • Hibernate - SortedSet Mapping
  • Hibernate - SortedMap Mapping
  • Hibernate - Native SQL
  • Hibernate - Logging by Log4j using xml File
  • Hibernate - Many-to-One Mapping
  • Hibernate - Logging By Log4j Using Properties File
  • Hibernate - Table Per Concrete Class Using Annotation
  • Hibernate - Table Per Subclass using Annotation
  • Hibernate - Interceptors
  • Hibernate - Many-to-Many Mapping
  • Hibernate - Types of Mapping
  • Hibernate - Criteria Queries
  • Hibernate - Table Per Hierarchy using Annotation
  • Hibernate - Table Per Subclass Example using XML File
  • Hibernate - Table Per Hierarchy using XML File
  • Hibernate - Create POJO Classes
  • Hibernate - Web Application
  • Hibernate - Table Per Concrete Class using XML File
  • Hibernate - Generator Classes
  • Hibernate - SQL Dialects
  • Hibernate - Query Language
  • Hibernate - Difference Between ORM and JDBC
  • Hibernate - Annotations
  • Hibernate Example using XML in Eclipse
  • Hibernate - Create Hibernate Configuration File with the Help of Plugin
  • Hibernate Example using JPA and MySQL
  • Hibernate - One-to-Many Mapping
  • Aspect Oriented Programming and AOP in Spring Framework
  • Spring - AOP Example (Spring1.2 Old Style AOP)
  • Spring - AOP AspectJ Xml Configuration
  • Spring AOP - AspectJ Annotation
  • Usage of @Before, @After, @Around, @AfterReturning, and @AfterThrowing in a Single Spring AOP Project

Spring Security

  • Introduction to Spring Security and its Features
  • Some Important Terms in Spring Security
  • OAuth2 Authentication with Spring and Github
  • Spring Security at Method Level
  • Spring - Security JSP Tag Library
  • Spring - Security Form-Based Authentication
  • Spring Security - Remember Me
  • Spring Security XML
  • Spring Security Project Example using Java Configuration
  • How to Change Default User and Password in Spring Security?
  • Spring - Add Roles in Spring Security
  • Spring - Add User Name and Password in Spring Security

Java Spring – Using @PropertySource Annotation and Resource Interface

In Java applications, Sometimes we might need to use data from external resources such as text files, XML files, properties files, image files, etc., from different locations (e.g., a file system, classpath, or URL). 

@PropertySource Annotation

To achieve this, the Spring framework provides the @PropertySource annotation as a facility to read and load the contents of a . properties file (i.e., key-value pairs) to set up bean properties in our application. 

We need to use this annotation along with PropertySourcesPlaceholderConfigurer class. This class resolves the placeholders within bean definition property values.

Resource Interface

In addition to this, Spring also has a resource loader mechanism that provides a unified Resource interface. Using this interface we can retrieve any type of external resource by a resource path. 

All we need to do is to specify different prefixes for this path to load resources from different locations with the @Value annotation. 

How it works

To demonstrate this concept, let’s take a simple example of a Shopping application in which we will be having different categories of products and their details listed. First, we create the ShoppingCategory.java class as follows:

 

Here, we are creating separate lists for each category of products. Now, we will create Product.java bean class to specify product variables and getter/setter methods.

   

Assume we have a series of values in a properties file we want to access to set up bean properties. Typically, a properties file can be the configuration properties of a database or some other application values composed of key values. In this example, we take the following discount rates (as key values) stored in a file called discounts.properties .

Now, we will create ShoppingCategoryConfig.java class as follows.

           

Here, we are using @PropertySource annotation with a value of classpath:discounts.properties in the Java config class. The classpath: prefix tells the Spring to search for the discounts.properties file in the Java classpath. Once we define the @PropertySource annotation to load the properties file, as we discussed earlier, we also need to define a PropertySourcePlaceholderConfigurer bean with the @Bean annotation. Then, Spring automatically wires the @ PropertySource – discounts.properties file. Now the properties in the file become accessible as bean properties. Next, we need to define Java variables to take values from the properties file. To do this, we need to use the @ Value annotation with a placeholder expression. The syntax is:

Then, a search is done for the key value in all the loaded application properties. If a matching key=value is found in the properties file, then the corresponding value is assigned to the bean property. If no matching value is found, default_value (i.e., after ${key:) is assigned to the bean property. To test this we need to create Main.java class as follows:

         

If we run the project, the output will be as follows.

Output

Output – @PropertySource annotation

Here we can see the discount values as the java variables are set up as the bean instances for a bean’s discount property. This is for reading the .properties file to set up bean instances. But, If we want to use properties file or any other file data for a different purpose than setting up bean properties, we should use Spring’s Resource mechanism. Let’s consider the same example, and we need to add some text that involves some offer details at the end of the shopping page. So, consider we have a text file with some data like below. 

To read this data into our application, we need to use the Resource interface as below in Main.java class.

           

Here, we are using the ClassPathResource , which tells the spring to look for the offer.txt file in the java classpath. And using the PropertiesLoaderUtils , it reads and loads all the content in the file. If the external resource file is not in the classpath but in some file system path, then we need to use FileSystemResource .

If the external resource file is at a URL, the resource would be loaded with UrlResource .

Now the output will be as follows.

Output

Output – Resource interface

The final project structure will be as follows:

project structure

Project Structure

This way, we can use the @PropertySource annotation and Resource interface to use the data from External Resources such as Text Files, XML Files, Properties Files, Image Files, etc. in our application.

Please Login to comment...

Similar reads, improve your coding skills with practice.

 alt=

What kind of Experience do you want to share?

Spring Read Classpath Resource using @Value

Tags: Spring Framework Resource Value Annotation Classpath

In this Java Spring Framework tutorial, we learn how to use @Value annotation to read classpath resource files located in the resources folder in your Spring application project.

For example, we have a text file located at /src/main/resources/data.json in the Spring application project.

Next step, we implement a new class named ResourceService and implement a method to read the data.json file and return it as a String object. In this service class we use @Value annotation to load the data.json file to the Resource object.

ResourceService.java import java.io.IOException ; import java.io.InputStream ; import org.springframework.beans.factory.annotation.Value ; import org.springframework.core.io.Resource ; import org.springframework.stereotype.Service ; import org.springframework.util.FileCopyUtils ; @Service public class ResourceService { @Value ( "classpath:data.json" ) private Resource dataResource ; public String readDataResourceAsString () throws IOException { InputStream inputStream = dataResource . getInputStream (); byte [] fileData = FileCopyUtils . copyToByteArray ( inputStream ); String outputString = new String ( fileData ); return outputString ; } }

How to use ResourceService class

Firstly, declare the resourceService object.

And return data.json file from classpath as a String object.

Happy Coding 😊

Java Guides

Java Guides

Search this blog, spring @importresource annotation example, create and import the spring boot application, the pom.xml file, project structure.

spring resource annotation classpath

Message.java

Messageservice.java, emailservice.java, smsservice.java, twitterservice.java, messageprocessor.java, messageprocessorimpl.java, the applicationcontext.xml file, running application.

spring resource annotation classpath

Read 25+ Spring Boot Articles with Source Code on GitHub -  Spring Boot Tutorial  

Related Spring and Spring Boot Tutorials/Guides:

Post a comment.

Leave Comment

My Top and Bestseller Udemy Courses

  • Spring 6 and Spring Boot 3 for Beginners (Includes Projects)
  • Building Real-Time REST APIs with Spring Boot
  • Building Microservices with Spring Boot and Spring Cloud
  • Full-Stack Java Development with Spring Boot 3 & React
  • Testing Spring Boot Application with JUnit and Mockito
  • Master Spring Data JPA with Hibernate
  • Spring Boot Thymeleaf Real-Time Web Application - Blog App

Check out all my Udemy courses and updates: Udemy Courses - Ramesh Fadatare

Copyright © 2018 - 2025 Java Guides All rights reversed | Privacy Policy | Contact | About Me | YouTube | GitHub

spring resource annotation classpath

HowToDoInJava

Read a File from Resources in Spring Boot

Lokesh Gupta

August 27, 2023

Learn to read a file from the ‘/resources’ folder in a Spring boot application using ClassPathResource class, ResourceLoader interface or @Value annotation.

To learn more about resource resolution in Spring, continue reading this tutorial.

1. Every File is a Resource in Spring

Spring’s  Resource  interface is used for abstracting access to low-level resources. After getting access to the Resource , we can use all its methods to get the file details and file content.

For quick reference, some of the important methods from the  Resource  interface are:

2. Resource Types in Spring

There are a number of  Resource  implementations inbuilt in Spring such as

  • ClassPathResource : loads a resource from the classpath. We can specify the path to the resource relative to the root of the classpath. It supports resolution as java.io.File if the class path resource resides in the filesystem but not for resources in a JAR. It recognizes the special prefix  'classpath:' on the string path.
  • UrlResource : Loads a resource from a URL. We can specify the URL of the resource with prefix 'http:' or ‘ file: ‘ if it is a file protocol.
  • FileSystemResource : Loads a resource from the file system. We can specify the absolute path to the resource on the file system with prefix 'file:' .
  • ServletContextResource : Loads a resource from the ServletContext . We can specify the path to the resource relative to the ServletContext . It does not use any prefixes .

3. Use ClassPathResource to Read from ‘/resources’ Directory

All files placed in the /resources directory are placed in the application root ‘/’ at the build time. We can access them using the ClassPathResource class using the following approaches.

3.1. Using ResourceLoader or ApplicationContext

Instead of using the constructor, we can also use ResourceLoader for loading resources. File paths can be fully qualified URLs, e.g. "file:C:/test.dat" or "classpath:test.dat" . It also supports relative file paths, e.g. "WEB-INF/test.dat" .

Note that ResourceLoader is automatically autowired using Spring’s dependency injection .

All application contexts implement the  ResourceLoader  interface, and therefore all application contexts may be used to obtain  Resource  instances.

3.2. Using Constructor

We can pass the file path along with the prefix to the constructor of a resource class, and Spring will automatically load it for us.

To read a file from inside a jar or war file (that has not been extracted by the application server), please use resource.getInputStream() .

3.3. Using @Value Annotation

We can also directly inject a file path into a Spring bean using the @Value annotation. Note that it eagerly loads the file .

4. Conclusion

Spring offers different implementations of the Resource interface to serve the resources from various sources, such as:

  • ClassPathResource : Loads a resource from the classpath using the ‘classpath:’ prefix.
  • UrlResource : Loads a resource from a URL with prefixes like ‘http:’ or ‘file:’.
  • FileSystemResource : Loads a resource from the file system using the ‘file:’ prefix.
  • ServletContextResource : Loads a resource from the ServletContext without any prefixes.

This tutorial discussed the ClassPathResource to read the files (JSON, XML files etc.) from the ‘ /src/main/resources ‘ directory.

Drop me your questions related to the read file from the resources folder in Spring .

Happy Learning !!

Further reading:

  • Spring: Reading an Internal or External Resource
  • Python Interview Questions and Answers
  • Python Strings
  • Read a File from Resources Directory
  • Java Concurrency Interview Questions
  • Spring Boot Interview Questions for Experienced Developers

guest

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.

Tutorial Series

Privacy Policy

REST API Tutorial

Spring Framework Guru

Working with resources in spring.

Spring Framework Guru

In this post, I’ll explain how to work with resources in Spring using ResourceLoader .

  • We’ll begin with a brief introduction about resources.
  • Next, we’ll look at the Resource  interface and some of its important methods.
  • Finally, we’ll go through its implementations.

Introduction: Working With Resources In Spring via ResourceLoader

Frequently, we need to read external resources into our Spring application.

Examples of external resources are text files, XML files, properties files, and image files.

These resources may be present at different locations. For example, in the file system, classpath, or URL.

Usually, we have to use different APIs for loading resources from different locations.

To handle such tasks, Spring provides the Resource and ResourceLoader interfaces. The Resource interface represents external resources. The ResourceLoader interface provides methods to load resources.

Spring Resource Interface

Resource is an interface in Spring to represent an external resource. Spring provides several implementations for the Resource interface.

The getResource() method of ResourceLoader decides the Resource implementation to use. This is determined by the resource path.

The code of the Resource interface is this.

As you can see, the Resource interface extends the InputStreamSource interface. Some of the important methods of the Resource  interface are:

  • getInputStream() : Locates and opens the resource. It returns an InputStream  for reading from the resource.
  • exists() : Returns a boolean indicating whether this resource actually exists in physical form.
  • isOpen() : Returns a boolean indicating whether this resource represents a handle with an open stream. If true, the InputStream must be read once only and then closed to avoid resource leaks. It will typically be false for resource implementations, with the exception of InputStreamResource .
  • getDescription() : Returns a description for this resource. The description can be used for error output when working with the resource. The description is often the fully qualified file name or the actual URL of the resource.

Spring’s Implementations for Resource Interface

Spring provides several implementations for the Resource  interface:

  • URLResource: Represents a resource loaded from a URL.
  • ClassPathResource: Represents a resource loaded from the classpath.
  • FileSystemResource: Represents a resource loaded from the filesystem.
  • ServletContextResource: This implementation is for ServletContext resources. This interprets relative paths within the relevant web application’s root directory.
  • InputStreamResource: Represents an input stream resource.
  • ByteArrayResource: Represents a byte array resource.

Let’s start coding for loading a resource using ResourceLoader .

Using Spring’s ResourceLoader To Get A Resource

First, let’s define the class ResourceLoaderService .

It has the showResourceDataUsingFilePath() method which contains getResource() method to load a text file from the path provided.

Here is the content of the ResourceLoaderService.java file.

ResourceLoaderService.java

Next, let’s write the main method.

With the help of Spring application context, we get the ResourceLoaderService object and call the showResourceDataUsingFilePath() using this object.

Below is an example which prints the content of loaded resources on the console.

How To Load External Resources

We can specify different prefixes for creating a path to load resources from different locations.

  • To load a resource from a file system, we use the file prefix.
  • Similarly, to load a resource from the classpath, we use the classpath prefix.
  • We may also specify a URL as a resource path.

Below are the ways to load external resources: Load resource from the application root folder To load a file from the application folder, use this. Resource resource = resourceLoader.getResource("file:data.txt");

Load resource from classpath To load a file from the classpath, use this. Resource resource = resourceLoader.getResource("classpath:data.txt");

Load resource from the filesystem To load a file from filesystem outside the application folder, use the below template: Resource resource = resourceLoader.getResource("file:c:/temp/filesystemdata.txt");

Load resource from URL Similarly, to load a file from any URL, use below template: Resource resource = resourceLoader.getResource("https://testsite.com/data.txt");

In conclusion, all the above examples will load the resource file from their location. You can choose the implementation that fits your requirements.

In this post, we’ve seen a few ways to access and read a resource using Spring. We looked at example implementations for loading resources present at

  • The classpath
  • The filesystem
  • Directly from any URL
  • Main application directory

You can download the complete source code of this post from GitHub .

  • resource loader

' src=

About SFG Contributor

Staff writer account for Spring Framework Guru

You May Also Like

JWT Token Authentication in Spring Boot Microservices

JWT Token Authentication in Spring Boot Microservices

Spring Framework Guru

Hikari Configuration for MySQL in Spring Boot 2

Spring Framework Guru

Database Migration with Flyway

Spring Framework 6

Getting Ready for Spring Framework 6

Using Filters in Spring Web Applications

Using Filters in Spring Web Applications

Bootstrapping Data in Spring Boot

Bootstrapping Data in Spring Boot

Hikari Connection Pool

Eureka Service Registry

Spring Framework Guru

Scheduling in Spring Boot

Spring for Apache Kafka

Spring for Apache Kafka

Spring retry.

Spring Boot CLI

Spring Boot CLI

Spring Framework Guru

Actuator in Spring Boot

Internationalization with Spring Boot

Internationalization with Spring Boot

One-to-one relationship in jpa.

Spring Framework Guru

The @RequestBody Annotation

Learn Spring

Spring BeanFactory vs ApplicationContext

MySQL Stored Procedures with Spring Boot

MySQL Stored Procedures with Spring Boot

Spring Framework Guru

Bean Validation in Spring Boot

Spring state machine.

Exception Handling in Spring Boot REST API

Exception Handling in Spring Boot REST API

Spring Boot Pagination

Spring Boot Pagination

Spring rest docs, using mapstruct with project lombok, argumentcaptor in mockito.

Spring Framework Guru

Reading External Configuration Properties in Spring

Api gateway with spring cloud.

Testing Spring Boot RESTful Services

Testing Spring Boot RESTful Services

Caching in Spring RESTful Service: Part 2 - Cache Eviction

Caching in Spring RESTful Service: Part 2 – Cache Eviction

Spring boot messaging with rabbitmq.

Caching in Spring Boot RESTful Service: Part 1

Caching in Spring Boot RESTful Service: Part 1

Spring Framework Guru

Implementing HTTP Basic Authentication in a Spring Boot REST API

Immutable Property Binding

Immutable Property Binding

Java Bean Properties Binding

Java Bean Properties Binding

External configuration data in spring.

Spring Data JPA @Query

Spring Data JPA @Query

Configuring mysql with circleci.

Fabric8 Docker Maven Plugin

Fabric8 Docker Maven Plugin

Feign REST Client for Spring Application

Feign REST Client for Spring Application

Docker Hub for Spring Boot

Docker Hub for Spring Boot

Consul miniseries: spring boot application and consul integration part 3, run spring boot on docker, consul miniseries: spring boot application and consul integration part 2.

Consul Miniseries: Spring Boot Application and Consul Integration Part 1

Consul Miniseries: Spring Boot Application and Consul Integration Part 1

Why You Should be Using Spring Boot Docker Layers

Why You Should be Using Spring Boot Docker Layers

Spring Bean Scopes

Spring Bean Scopes

Debug your code in intellij idea, stay at home, learn from home with 6 free online courses.

What is the best UI to Use with Spring Boot?

What is the best UI to Use with Spring Boot?

Best Practices for Dependency Injection with Spring

Best Practices for Dependency Injection with Spring

Should I Use Spring REST Docs or OpenAPI?

Should I Use Spring REST Docs or OpenAPI?

Spring boot with lombok: part 1.

Spring Framework Guru

Using Project Lombok with Gradle

Spring bean lifecycle, spring profiles, spring bean definition inheritance, autowiring in spring.

spring boot

What is New in Spring Boot 2.2?

Using Ehcache 3 in Spring Boot

Using Ehcache 3 in Spring Boot

How to configure multiple data sources in a spring boot application.

Using RestTemplate with Apaches HttpClient

Using RestTemplate with Apaches HttpClient

Using RestTemplate in Spring

Using RestTemplate in Spring

Using spring aware interfaces, service locator pattern in spring, using graphql in a spring boot application, spring jdbctemplate crud operations, contracts for microservices with openapi and spring cloud contract, using swagger request validator to validate spring cloud contracts, spring 5 webclient, defining spring cloud contracts in open api.

Hibernate Show SQL

Hibernate Show SQL

Spring Component Scan

Spring Component Scan

Using CircleCI to Build Spring Boot Microservices

Using CircleCI to Build Spring Boot Microservices

Spring framework annotations.

Using JdbcTemplate with Spring Boot and Thymeleaf

Using JdbcTemplate with Spring Boot and Thymeleaf

Using the spring @requestmapping annotation.

Spring Data MongoDB with Reactive MongoDB

Spring Data MongoDB with Reactive MongoDB

Spring Boot with Embedded MongoDB

Spring Boot with Embedded MongoDB

Spring Web Reactive

Spring Web Reactive

What are Reactive Streams in Java?

What are Reactive Streams in Java?

Spring Framework 5

What’s new in Spring Framework 5?

Spring Boot RESTful API Documentation with Swagger 2

Spring Boot RESTful API Documentation with Swagger 2

Mockito Mock vs Spy in Spring Boot Tests

Mockito Mock vs Spy in Spring Boot Tests

Spring Boot Mongo DB Example Application

Spring Boot Mongo DB Example Application

Configuring Spring Boot for MariaDB

Configuring Spring Boot for MariaDB

Spring boot web application, part 6 – spring security with dao authentication provider.

Configuring Spring Boot for MongoDB

Configuring Spring Boot for MongoDB

Spring Boot Web Application, Part 5 - Spring Security

Spring Boot Web Application, Part 5 – Spring Security

Chuck Norris for Spring Boot Actuator

Chuck Norris for Spring Boot Actuator

Testing spring mvc with spring boot 1.4: part 1, running spring boot in a docker container.

Jackson Dependency Issue in Spring Boot with Maven Build

Jackson Dependency Issue in Spring Boot with Maven Build

Using YAML in Spring Boot to Configure Logback

Using YAML in Spring Boot to Configure Logback

Using Logback with Spring Boot

Using Logback with Spring Boot

Using Log4J 2 with Spring Boot

Using Log4J 2 with Spring Boot

Fixing nouniquebeandefinitionexception exceptions, samy is my hero and hacking the magic of spring boot.

2015 Year in Review

2015 Year in Review

Configuring Spring Boot for PostgreSQL

Configuring Spring Boot for PostgreSQL

Embedded JPA Entities Under Spring Boot and Hibernate Naming

Embedded JPA Entities Under Spring Boot and Hibernate Naming

Spring Boot Developer Tools

Spring Boot Developer Tools

Spring beanfactoryaware interface.

Spring BeanNameAware Interface

Spring BeanNameAware Interface

Displaying list of objects in table using thymeleaf.

Using H2 and Oracle with Spring Boot

Using H2 and Oracle with Spring Boot

Configuring Spring Boot for Oracle

Configuring Spring Boot for Oracle

Spring Boot Web Application - Part 4 - Spring MVC

Spring Boot Web Application – Part 4 – Spring MVC

Configuring Spring Boot for MySQL

Configuring Spring Boot for MySQL

Spring Boot Example of Spring Integration and ActiveMQ

Spring Boot Example of Spring Integration and ActiveMQ

How do i become a java web developer.

Spring Boot Web Application - Part 3 - Spring Data JPA

Spring Boot Web Application – Part 3 – Spring Data JPA

Spring Boot Web Application - Part 2 - Using ThymeLeaf

Spring Boot Web Application – Part 2 – Using ThymeLeaf

Spring Boot Web Application - Part 1 - Spring Initializr

Spring Boot Web Application – Part 1 – Spring Initializr

Using the H2 Database Console in Spring Boot with Spring Security

Using the H2 Database Console in Spring Boot with Spring Security

Running code on spring boot startup, integration testing with spring and junit.

polyglot programming

Polyglot Programming in Spring

Using Spring Integration Futures

Using Spring Integration Futures

Using the spring framework for enterprise application development.

Testing Spring Integration Gateways

Testing Spring Integration Gateways

Introduction to Spring Expression Language (SpEL)

Introduction to Spring Expression Language (SpEL)

Hello World Using Spring Integration

Hello World Using Spring Integration

Creating Spring Beans

Creating Spring Beans

Dependency Injection Example Using Spring

Dependency Injection Example Using Spring

Hello World With Spring 4

Hello World With Spring 4

Getting started with spring boot.

What's all the fuss about Java Lambdas?

What’s all the fuss about Java Lambdas?

Leave a reply cancel reply.

Your email address will not be published. Required fields are marked *

Save my name, email, and website in this browser for the next time I comment.

This site uses Akismet to reduce spam. Learn how your comment data is processed .

Spring ClassPathResource tutorial

last modified October 18, 2023

Spring ClassPathResource tutorial shows how to read resources with a ClassPathResource in a Spring application.

Spring ClassPathResource

ClassPathResource allows to obtain resources from a Java classpath.

Spring ClassPathResource example

The application reads text data from a file located in the Java classpath.

This is the project structure.

In the pom.xml file, we have basic Spring dependencies spring-core and spring-context and logging logback-classic dependency.

The exec-maven-plugin is used for executing Spring application from the Maven on the command line.

The resources directory is included in the classpath. The application reads words from the words.txt file.

The logback.xml is a configuration file for the Logback logging library.

The ClassPathResource is used to locate the text file.

This is the main application class.

We retrieve the readWordsService bean from the container and call its readWords method. The words are printed to the console.

We run the application.

In this article we have worked with Spring's ClassPathResource .

My name is Jan Bodnar and I am a passionate programmer with many years of programming experience. I have been writing programming articles since 2007. So far, I have written over 1400 articles and 8 e-books. I have over eight years of experience in teaching programming.

Wiring in Spring: @Autowired, @Resource and @Inject

Last updated: May 11, 2024

spring resource annotation classpath

  • Spring Core Basics

announcement - icon

Java applications have a notoriously slow startup and a long warmup time. The CRaC (Coordinated Restore at Checkpoint) project from OpenJDK can help improve these issues by creating a checkpoint with an application's peak performance and restoring an instance of the JVM to that point.

To take full advantage of this feature, BellSoft provides containers that are highly optimized for Java applications. These package Alpaquita Linux (a full-featured OS optimized for Java and cloud environment) and Liberica JDK (an open-source Java runtime based on OpenJDK).

These ready-to-use images allow us to easily integrate CRaC in a Spring Boot application:

Improve Java application performance with CRaC support

Modern software architecture is often broken. Slow delivery leads to missed opportunities, innovation is stalled due to architectural complexities, and engineering resources are exceedingly expensive.

Orkes is the leading workflow orchestration platform built to enable teams to transform the way they develop, connect, and deploy applications, microservices, AI agents, and more.

With Orkes Conductor managed through Orkes Cloud, developers can focus on building mission critical applications without worrying about infrastructure maintenance to meet goals and, simply put, taking new products live faster and reducing total cost of ownership.

Try a 14-Day Free Trial of Orkes Conductor today.

Azure Container Apps is a fully managed serverless container service that enables you to build and deploy modern, cloud-native Java applications and microservices at scale. It offers a simplified developer experience while providing the flexibility and portability of containers.

Of course, Azure Container Apps has really solid support for our ecosystem, from a number of build options, managed Java components, native metrics, dynamic logger, and quite a bit more.

To learn more about Java features on Azure Container Apps, you can get started over on the documentation page .

And, you can also ask questions and leave feedback on the Azure Container Apps GitHub page .

Whether you're just starting out or have years of experience, Spring Boot is obviously a great choice for building a web application.

Jmix builds on this highly powerful and mature Boot stack, allowing devs to build and deliver full-stack web applications without having to code the frontend. Quite flexibly as well, from simple web GUI CRUD applications to complex enterprise solutions.

Concretely, The Jmix Platform includes a framework built on top of Spring Boot, JPA, and Vaadin , and comes with Jmix Studio, an IntelliJ IDEA plugin equipped with a suite of developer productivity tools.

The platform comes with interconnected out-of-the-box add-ons for report generation, BPM, maps, instant web app generation from a DB, and quite a bit more:

>> Become an efficient full-stack developer with Jmix

Get non-trivial analysis (and trivial, too!) suggested right inside your IDE or Git platform so you can code smart, create more value, and stay confident when you push.

Get CodiumAI for free and become part of a community of over 280,000 developers who are already experiencing improved and quicker coding.

Write code that works the way you meant it to:

>> CodiumAI. Meaningful Code Tests for Busy Devs

DbSchema is a super-flexible database designer, which can take you from designing the DB with your team all the way to safely deploying the schema .

The way it does all of that is by using a design model , a database-independent image of the schema, which can be shared in a team using GIT and compared or deployed on to any database.

And, of course, it can be heavily visual, allowing you to interact with the database using diagrams, visually compose queries, explore the data, generate random data, import data or build HTML5 database reports.

>> Take a look at DBSchema

Slow MySQL query performance is all too common. Of course it is. A good way to go is, naturally, a dedicated profiler that actually understands the ins and outs of MySQL.

The Jet Profiler was built for MySQL only , so it can do things like real-time query performance, focus on most used tables or most frequent queries, quickly identify performance issues and basically help you optimize your queries.

Critically, it has very minimal impact on your server's performance, with most of the profiling work done separately - so it needs no server changes, agents or separate services.

Basically, you install the desktop application, connect to your MySQL server , hit the record button, and you'll have results within minutes:

>> Try out the Profiler

Do JSON right with Jackson

Download the E-book

Get the most out of the Apache HTTP Client

Get Started with Apache Maven:

Working on getting your persistence layer right with Spring?

Explore the eBook

Building a REST API with Spring?

Explore Spring Boot 3 and Spring 6 in-depth through building a full REST API with the framework:

>> REST With Spring (new)

Get started with Spring and Spring Boot, through the reference Learn Spring course:

>> LEARN SPRING

The AI Assistant to boost Boost your productivity writing unit tests - Machinet AI .

AI is all the rage these days, but for very good reason. The highly practical coding companion, you'll get the power of AI-assisted coding and automated unit test generation . Machinet's Unit Test AI Agent utilizes your own project context to create meaningful unit tests that intelligently aligns with the behavior of the code. And, the AI Chat crafts code and fixes errors with ease, like a helpful sidekick.

Simplify Your Coding Journey with Machinet AI :

>> Install Machinet AI in your IntelliJ

Yes, Spring Security can be complex, from the more advanced functionality within the Core to the deep OAuth support in the framework.

I built the security material as two full courses - Core and OAuth , to get practical with these more complex scenarios. We explore when and how to use each feature and code through it on the backing project .

You can explore the course here:

>> Learn Spring Security

Spring Data JPA is a great way to handle the complexity of JPA with the powerful simplicity of Spring Boot .

Get started with Spring Data JPA through the guided reference course:

>> CHECK OUT THE COURSE

1. Overview

In this Spring Framework tutorial, we’ll demonstrate how to use annotations related to dependency injection, namely the @Resource , @Inject , and @Autowired annotations. These annotations provide classes with a declarative way to resolve dependencies:

As opposed to instantiating them directly (the imperative way):

Two of the three annotations belong to the Java extension package: javax.annotation.Resource and javax.inject.Inject . The @Autowired annotation belongs to the org.springframework.beans.factory.annotation package.

Each of these annotations can resolve dependencies either by field injection or by setter injection. We’ll use a simplified, but practical example to demonstrate the distinction between the three annotations, based on the execution paths taken by each annotation.

The examples will focus on how to use the three injection annotations during integration testing. The dependency required by the test can either be an arbitrary file or an arbitrary class.

Further reading:

Constructor dependency injection in spring, intro to inversion of control and dependency injection with spring, using @autowired in abstract classes, 2. the @resource a nnotation.

The @Resource annotation is part of the JSR-250 annotation collection, and is packaged with Jakarta EE. This annotation has the following execution paths, listed by precedence:

  • Match by Name
  • Match by Type
  • Match by Qualifier

These execution paths are applicable to both setter and field injection.

2.1. Field Injection

We can resolve dependencies by field injection by annotating an instance variable with the @Resource annotation.

2.1.1. Match by Name

We’ll use the following integration test to demonstrate match-by-name field injection:

Let’s go through the code. In the FieldResourceInjectionTest integration test, at line 7, we resolved the dependency by name by passing in the bean name as an attribute value to the @Resource annotation:

This configuration will resolve dependencies using the match-by-name execution path. We must define the bean namedFile in the ApplicationContextTestResourceNameType application context.

Note that the bean id and the corresponding reference attribute value must match:

If we fail to define the bean in the application context, it will result in an org.springframework.beans.factory.NoSuchBeanDefinitionException being thrown. We can demonstrate this by changing the attribute value passed into the @Bean annotation in the ApplicationContextTestResourceNameType application context, or changing the attribute value passed into the @Resource annotation in the FieldResourceInjectionTest integration test.

2.1.2. Match by Type

To demonstrate the match-by-type execution path, we just remove the attribute value at line 7 of the FieldResourceInjectionTest integration test:

Then we run the test again.

The test will still pass because if the @Resource annotation doesn’t receive a bean name as an attribute value, the Spring Framework will proceed with the next level of precedence, match-by-type, in order to try resolve the dependency.

2.1.3. Match by Qualifier

To demonstrate the match-by-qualifier execution path, the integration testing scenario will be modified so that there are two beans defined in the ApplicationContextTestResourceQualifier application context:

We’ll use the QualifierResourceInjectionTest integration test to demonstrate match-by-qualifier dependency resolution. In this scenario, a specific bean dependency needs to be injected into each reference variable:

When we run the integration test, an org.springframework.beans.factory.NoUniqueBeanDefinitionException will be thrown. This will happen because the application context will find two bean definitions of type File , and won’t know which bean should resolve the dependency.

To resolve this issue, we need to refer to line 7 to line 10 of the QualifierResourceInjectionTest integration test:

We have to add the following lines of code:

So that the code block looks as follows:

When we run the integration test again, it should pass. Our test demonstrates that even if we define multiple beans in an application context, we can use the @Qualifier annotation to clear any confusion by allowing us to inject specific dependencies into a class.

2.2. Setter Injection

The execution paths taken when injecting dependencies on a field are applicable to setter-based injection as well.

2.2.1. Match by Name

The only difference is the MethodResourceInjectionTest integration test has a setter method:

We resolve dependencies by setter injection by annotating a reference variable’s corresponding setter method. Then we pass the name of the bean dependency as an attribute value to the @Resource annotation:

We’ll reuse the namedFile bean dependency in this example. The bean name and the corresponding attribute value must match.

When we run the integration test, it will pass.

In order for us to verify that the match-by-name execution path resolved the dependency, we need to change the attribute value passed to the @Resource annotation to a value of our choice and run the test again. This time, the test will fail with a NoSuchBeanDefinitionException .

2.2.2. Match by Type

To demonstrate setter-based, match-by-type execution, we will use the MethodByTypeResourceTest integration test:

When we run this test, it will pass.

In order for us to verify that the match-by-type execution path resolved the File dependency, we need to change the class type of the defaultFile variable to another class type like String . Then we can execute the MethodByTypeResourceTest integration test again, and this time a NoSuchBeanDefinitionException will be thrown.

The exception verifies that match-by-type was indeed used to resolve the File dependency. The NoSuchBeanDefinitionException confirms that the reference variable name doesn’t need to match the bean name. Instead, dependency resolution depends on the bean’s class type matching the reference variable’s class type.

2.2.3. Match by Qualifier

We will use the MethodByQualifierResourceTest integration test to demonstrate the match-by-qualifier execution path:

Our test demonstrates that even if we define multiple bean implementations of a particular type in an application context, we can use a @Qualifier annotation together with the @Resource annotation to resolve a dependency.

Similar to field-based dependency injection, if we define multiple beans in an application context, we must use a  @Qualifier  annotation to specify which bean to use to resolve dependencies, or a NoUniqueBeanDefinitionException will be thrown.

3. The @Inject Annotation

The @Inject annotation belongs to the JSR-330 annotations collection. This annotation has the following execution paths, listed by precedence:

These execution paths are applicable to both setter and field injection. In order for us to access the @Inject annotation, we have to declare the javax.inject library as a Gradle or Maven dependency.

For Gradle:

3.1. Field Injection

3.1.1. match by type.

We’ll modify the integration test example to use another type of dependency, namely the ArbitraryDependency class. The ArbitraryDependency class dependency merely serves as a simple dependency and holds no further significance:

Here’s the FieldInjectTest integration test in question:

Unlike the @Resource annotation, which resolves dependencies by name first, the default behavior of the @Inject annotation is to resolve dependencies by type.

This means that even if the class reference variable name differs from the bean name, the dependency will still be resolved, provided that the bean is defined in the application context. Note how the reference variable name in the following test:

differs from the bean name configured in the application context:

When we execute the test, we’re able to resolve the dependency.

3.1.2. Match by Qualifier

What if there are multiple implementations of a particular class type, and a certain class requires a specific bean? Let’s modify the integration testing example so that it requires another dependency.

In this example, we subclass the ArbitraryDependency class, used in the match-by-type example, to create the AnotherArbitraryDependency class:

The objective of each test case is to ensure that we inject each dependency correctly into each reference variable:

We can use the FieldQualifierInjectTest integration test to demonstrate match by qualifier:

If we have multiple implementations of a particular class in an application context, and the FieldQualifierInjectTest integration test attempts to inject the dependencies in the manner listed below, a NoUniqueBeanDefinitionException will be thrown:

Throwing this exception is the Spring Framework’s way of pointing out that there are multiple implementations of a certain class and it is confused about which one to use. In order to elucidate the confusion, we can go to line 7 and 10 of the FieldQualifierInjectTest integration test:

We can pass the required bean name to the @Qualifier annotation, which we use together with the @Inject annotation. This is how the code block will now look:

The @Qualifier annotation expects a strict match when receiving a bean name. We must ensure that the bean name is passed to the Qualifier correctly, otherwise, a NoUniqueBeanDefinitionException will be thrown. If we run the test again, it should pass.

3.1.3. Match by Name

The FieldByNameInjectTest integration test used to demonstrate match by name is similar to the match by type execution path. The only difference is now we require a specific bean, as opposed to a specific type. In this example, we subclass the ArbitraryDependency class again to produce the YetAnotherArbitraryDependency class:

In order to demonstrate the match-by-name execution path, we will use the following integration test:

We list the application context:

If we run the integration test, it will pass.

In order to verify that we injected the dependency by the match-by-name execution path, we need to change the value, yetAnotherFieldInjectDependency , that was passed in to the @Named annotation to another name of our choice. When we run the test again, a NoSuchBeanDefinitionException will be thrown.

3.2. Setter Injection

Setter-based injection for the @Inject annotation is similar to the approach used for the @Resource setter-based injection. Instead of annotating the reference variable, we annotate the corresponding setter method. The execution paths followed by field-based dependency injection also apply to setter based injection.

4. The @Autowired Annotation

The behaviour of the @Autowired annotation is similar to the @Inject annotation. The only difference is that the @Autowired annotation is part of the Spring framework. This annotation has the same execution paths as the @Inject annotation, listed in order of precedence:

4.1. Field Injection

4.1.1. match by type.

The integration testing example used to demonstrate the @Autowired match-by-type execution path will be similar to the test used to demonstrate the @Inject match-by-type execution path. We use the following FieldAutowiredTest integration test to demonstrate match-by-type using the @Autowired annotation:

We list the application context for this integration test:

We use this integration test to demonstrate that match-by-type takes first precedence over the other execution paths. Notice the reference variable name on line 8 of the FieldAutowiredTest integration test:

This is different than the bean name in the application context:

When we run the test, it should pass.

In order to confirm that the dependency was indeed resolved using the match-by-type execution path, we need to change the type of the fieldDependency reference variable and run the integration test again. This time, the FieldAutowiredTest integration test will fail, with a NoSuchBeanDefinitionException being thrown. This verifies that we used match-by-type to resolve the dependency.

4.1.2. Match by Qualifier

What if we’re faced with a situation where we’ve defined multiple bean implementations in the application context:

If we execute the following FieldQualifierAutowiredTest integration test, a NoUniqueBeanDefinitionException will be thrown:

The exception is due to the ambiguity caused by the two beans defined in the application context. The Spring Framework doesn’t know which bean dependency should be autowired to which reference variable. We can resolve this issue by adding the @Qualifier annotation to lines 7 and 10 of the FieldQualifierAutowiredTest integration test:

so that the code block looks as follows:

When we run the test again, it will pass.

4.1.3. Match by Name

We’ll use the same integration test scenario to demonstrate the match-by-name execution path using the @Autowired annotation to inject a field dependency. When autowiring dependencies by name, the @ComponentScan annotation must be used with the application context, ApplicationContextTestAutowiredName :

We use the @ComponentScan annotation to search packages for Java classes that have been annotated with the @Component annotation. For example, in the application context, the com.baeldung.dependency package will be scanned for classes that have been annotated with the @Component annotation. In this scenario, the Spring Framework must detect the ArbitraryDependency class, which has the @Component annotation:

The attribute value, autowiredFieldDependency , passed into the @Component annotation, tells the Spring Framework that the ArbitraryDependency class is a component named autowiredFieldDependency . In order for the @Autowired annotation to resolve dependencies by name, the component name must correspond with the field name defined in the FieldAutowiredNameTest integration test; please refer to line 8:

When we run the FieldAutowiredNameTest integration test, it will pass.

But how do we know that the @Autowired annotation really did invoke the match-by-name execution path? We can change the name of the reference variable autowiredFieldDependency to another name of our choice, then run the test again.

This time, the test will fail and a NoUniqueBeanDefinitionException is thrown. A similar check would be to change the @Component attribute value, autowiredFieldDependency , to another value of our choice and run the test again. A NoUniqueBeanDefinitionException will also be thrown.

This exception is proof that if we use an incorrect bean name, no valid bean will be found. That’s how we know the match-by-name execution path was invoked.

4.2. Setter Injection

Setter-based injection for the @Autowired annotation is similar to the approach demonstrated for the @Resource setter-based injection. Instead of annotating the reference variable with the @Inject annotation, we annotate the corresponding setter. The execution paths followed by field-based dependency injection also apply to setter-based injection.

5. Applying These Annotations

This raises the question of which annotation should be used and under what circumstances. The answer to these questions depends on the design scenario faced by the application in question, and how the developer wishes to leverage polymorphism based on the default execution paths of each annotation.

5.1. Application-Wide Use of Singletons Through Polymorphism

If the design is such that application behaviors are based on implementations of an interface or an abstract class, and these behaviors are used throughout the application, then we can use either the @Inject or @Autowired annotation.

The benefit of this approach is that when we upgrade the application, or apply a patch in order to fix a bug, classes can be swapped out with minimal negative impact to the overall application behavior. In this scenario, the primary default execution path is match-by-type.

5.2. Fine-Grained Application Behavior Configuration Through Polymorphism

If the design is such that the application has complex behavior, each behavior is based on different interfaces/abstract classes, and the usage of each of these implementations varies across the application, then we can use the @Resource annotation. In this scenario, the primary default execution path is match-by-name.

5.3. Dependency Injection Should Be Handled Solely by the Jakarta EE Platform

If there is a design mandate for all dependencies to be injected by the Jakarta EE Platform as opposed to Spring, then the choice is between the @Resource annotation and the @Inject annotation. We should narrow down the final decision between the two annotations based on which default execution path is required.

5.4. Dependency Injection Should Be Handled Solely by the Spring Framework

If the mandate is for all dependencies to be handled by the Spring Framework, the only choice is the @Autowired annotation.

5.5. Discussion Summary

The table below summarizes our discussion.

Scenario @Resource @Inject @Autowired
Application-wide use of singletons through polymorphism
Fine-grained application behavior configuration through polymorphism
Dependency injection should be handled solely by the Jakarta EE platform
Dependency injection should be handled solely by the Spring Framework

6. Conclusion

In this article, we aimed to provide a deeper insight into the behavior of each annotation. Understanding how each annotation behaves will contribute to better overall application design and maintenance.

The code used during the discussion can be found on GitHub .

Slow MySQL query performance is all too common. Of course it is.

The Jet Profiler was built entirely for MySQL , so it's fine-tuned for it and does advanced everything with relaly minimal impact and no server changes.

Looking for the ideal Linux distro for running modern Spring apps in the cloud?

Meet Alpaquita Linux : lightweight, secure, and powerful enough to handle heavy workloads.

This distro is specifically designed for running Java apps . It builds upon Alpine and features significant enhancements to excel in high-density container environments while meeting enterprise-grade security standards.

Specifically, the container image size is ~30% smaller than standard options, and it consumes up to 30% less RAM:

>> Try Alpaquita Containers now.

Just published a new writeup on how to run a standard Java/Boot application as a Docker container, using the Liberica JDK on top of Alpaquita Linux:

>> Spring Boot Application on Liberica Runtime Container.

Explore the secure, reliable, and high-performance Test Execution Cloud built for scale. Right in your IDE:

Basically, write code that works the way you meant it to.

AI is all the rage these days, but for very good reason. The highly practical coding companion, you'll get the power of AI-assisted coding and automated unit test generation . Machinet's Unit Test AI Agent utilizes your own project context to create meaningful unit tests that intelligently aligns with the behavior of the code.

Get started with Spring Boot and with core Spring, through the Learn Spring course:

Build your API with SPRING - book cover

Follow the Spring Category

spring resource annotation classpath

DZone

  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
  • Manage My Drafts

Database Systems: In 2024, the focus around databases is on their ability to scale and perform in modern data architectures. See why.

Data Pipeline Essentials: Dive into the fundamentals of data pipelines and the problems it solves for modern enterprises.

2024 Kubernetes survey: Share your insights on containers, K8s, CI/CD, and DevOps (+ enter a $750 raffle!) for our upcoming Trend Report.

Natural Language Processing: Learn all of the cutting-edge NLP techniques! * Affiliate

  • Spring Beans With Auto-Generated Implementations: How-To
  • The ABCs of Unity's Coroutines: From Basics to Implementation
  • React, Angular, and Vue.js: What’s the Technical Difference?
  • In-Depth Guide to Using useMemo() Hook in React
  • API Implementation on AWS Serverless Architecture
  • From Code to Insight: Using NLP and Sentiment Analysis in Git History
  • A Hands-On Guide To OpenTelemetry: Intro to Observability
  • Optimizing MySQL Performance: Best Practices for Database Efficiency

Working With Resources in Spring

Learn how to use the resourceloader in your spring apps..

John Thompson user avatar

Join the DZone community and get the full member experience.

In this post, I’ll explain how to work with resources in Spring using ResourceLoader .

  • We’ll begin with a brief introduction about resources.
  • Next, we’ll look at the Resource interface and some of its important methods.
  • Finally, we’ll go through its implementations.

Picture of Resource Spring

Introduction: Working With Resources in Spring Via ResourceLoader

Frequently, we need to read external resources into our Spring application. Examples of external resources are text files, XML files, properties files, and image files. These resources may be present at different locations. For example, in the file system, classpath, or URL.

Usually, we have to use different APIs for loading resources from different locations.

To handle such tasks, Spring provides the Resource and ResourceLoader interfaces. The Resource interface represents external resources. The ResourceLoader interface provides methods to load resources.

Spring Resource Interface

Resource is an interface in Spring to represent an external resource. Spring provides several implementations for the Resource interface.

The getResource() method of ResourceLoader decides the Resource implementation to use. This is determined by the resource path.

The code of the Resource interface is this.

As you can see, the Resource interface extends the InputStreamSource interface. Some of the important methods of the Resource interface are:

  • getInputStream() : Locates and opens the resource. It returns an InputStream for reading from the resource.
  • exists() : Returns a boolean indicating whether this resource actually exists in physical form.
  • isOpen() : Returns a boolean indicating whether this resource represents a handle with an open stream. If true, the InputStream must be read once only and then closed to avoid resource leaks. It will typically be false for resource implementations, with the exception of InputStreamResource .
  • getDescription() : Returns a description for this resource. The description can be used for error output when working with the resource. The description is often the fully qualified file name or the actual URL of the resource.

Spring’s Implementations for Resource Interface

Spring provides several implementations for the Resource interface:

  • URLResource : Represents a resource loaded from a URL.
  • ClassPathResource : Represents a resource loaded from the classpath.
  • FileSystemResource : Represents a resource loaded from the filesystem.
  • ServletContextResource : This implementation is for ServletContext resources. This interprets relative paths within the relevant web application’s root directory.
  • InputStreamResource : Represents an input stream resource.
  • ByteArrayResource : Represents a byte array resource.

Let’s start coding for loading a resource using ResourceLoader.

Using Spring’s ResourceLoader to Get a Resource

First, let’s define the class ResourceLoaderService .

It has the showResourceDataUsingFilePath() method, which contains the getResource() method to load a text file from the path provided.

Here is the content of the ResourceLoaderService.java file.

ResourceLoaderService.java

Next, let’s write the main method.

With the help of the Spring application context, we get the ResourceLoaderService object and call the showResourceDataUsingFilePath() using this object.

Below is an example the prints the content of loaded resources on the console.

How to Load External Resources

We can specify different prefixes for creating a path to load resources from different locations.

  • To load a resource from a file system, we use the file prefix.
  • Similarly, to load a resource from the classpath, we use the classpath prefix.
  • We may also specify a URL as a resource path.

Below are the ways to load external resources:

Load resource from the application root folder To load a file from the application folder, use this: Resource resource = resourceLoader.getResource("file:data.txt");  

Load resource from classpath To load a file from the classpath, use this: Resource resource = resourceLoader.getResource("classpath:data.txt");  

Load resource from the filesystem To load a file from filesystem outside the application folder, use the below template: Resource resource = resourceLoader.getResource("file:c:/temp/filesystemdata.txt");

Load resource from URL Similarly, to load a file from any URL, use the below template: Resource resource = resourceLoader.getResource("https://testsite.com/data.txt");

In conclusion, all the above examples will load the resource file from their location. You can choose the implementation that fits your requirements.

In this post, we’ve seen a few ways to access and read a resource using Spring. We looked at example implementations for loading resources present at:

  • The classpath
  • The filesystem
  • Directly from any URL
  • Main application directory

You can download the complete source code of this post from GitHub .

Published at DZone with permission of John Thompson , DZone MVB . See the original article here.

Opinions expressed by DZone contributors are their own.

Partner Resources

  • About DZone
  • Send feedback
  • Community research
  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone
  • Terms of Service
  • Privacy Policy
  • 3343 Perimeter Hill Drive
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

Navigation Menu

Search code, repositories, users, issues, pull requests..., provide feedback.

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly.

To see all available qualifiers, see our documentation .

  • Notifications You must be signed in to change notification settings

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement . We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Host name 'www.googleapis.com' does not match the certificate subject provided by the peer #68

@sagarrao

sagarrao commented May 6, 2015

We have a project which is used to send Google now cards from andriod apps, to users who have registered for the same through the app.

To accomplish this, I have written a controller, for eg, to add the credentials of a user to our data store(redis) so that he would be registered for sending the cards.This is exactly as per the google now api documentations and the current code uses google oauth api client and we thought of using spring-social for establishing the oauth2 connection from the controller. the reason we can't use the google apis is that it is tightly coupled with the google data store and we want to move away from the google app engine.

The controller receives 2 inputs as part of the request as per the documentation :

Exchanges an authorization code for a long-lived refresh token and stores the token. Accepts a user ID and authorization code as POST params sent from the client app. The retrieved refresh token is stored in a DataStore keyed to the user ID. Note that this is the user's ID in your app, as opposed to the user
ID associated with the Google account in the Now API.

I use the authcode in the following manner:

GoogleConnectionFactory connectionFactory = new GoogleConnectionFactory("clientId", "clientSecret");
AccessGrant accessGrant = new AccessGrant(authCode); // sent as request parameter.
Connection connection = connectionFactory.createConnection(accessGrant);

This is the exception that's thrown:

2015-05-06 18:34:45.835 ERROR 9488 --- [nio-8443-exec-3] o.a.c.c.C.[.[.[/].[disp
atcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context
with path [] threw exception [Request processing failed; nested exception is or
g.springframework.web.client.ResourceAccessException: I/O error on GET request f
or "https://www.googleapis.com/plus/v1/people/me":Host name 'www.googleapis.com'
does not match the certificate subject provided by the peer (CN= .storage.googleapi
s.com, O=Google Inc, L=Mountain View, ST=California, C=US)] with root cause

javax.net.ssl.SSLPeerUnverifiedException: Host name 'www.googleapis.com' does no
t match the certificate subject provided by the peer (CN=*.storage.googleapis.co
m, O=Google Inc, L=Mountain View, ST=California, C=US)
at org.apache.http.conn.ssl.SSLConnectionSocketFactory.verifyHostname(SS
LConnectionSocketFactory.java:466)
at org.apache.http.conn.ssl.SSLConnectionSocketFactory.createLayeredSock
et(SSLConnectionSocketFactory.java:396)
at org.apache.http.conn.ssl.SSLConnectionSocketFactory.connectSocket(SSL
ConnectionSocketFactory.java:354)
at org.apache.http.impl.conn.DefaultHttpClientConnectionOperator.connect
(DefaultHttpClientConnectionOperator.java:134)
at org.apache.http.impl.conn.PoolingHttpClientConnectionManager.connect(
PoolingHttpClientConnectionManager.java:353)
at org.apache.http.impl.execchain.MainClientExec.establishRoute(MainClie
ntExec.java:380)
at org.apache.http.impl.execchain.MainClientExec.execute(MainClientExec.
java:236)
at org.apache.http.impl.execchain.ProtocolExec.execute(ProtocolExec.java
:184)
at org.apache.http.impl.execchain.RetryExec.execute(RetryExec.java:88)
at org.apache.http.impl.execchain.RedirectExec.execute(RedirectExec.java
:110)
at org.apache.http.impl.client.InternalHttpClixecute(InternalHttpClient.
java:184)
at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttp
Client.java:82)
at org.springframework.http.client.HttpComponentsClientHttpRequest.execu
teInternal(HttpComponentsClientHttpRequest.java:91)
at org.springframework.http.client.AbstractBufferingClientHttpRequest.ex
ecuteInternal(AbstractBufferingClientHttpRequest.java:48)
at org.springframework.http.client.AbstractClientHttpRequest.execute(Abs
tractClientHttpRequest.java:53)
at org.springframework.http.client.InterceptingClientHttpRequest$Request
Execution.execute(InterceptingClientHttpRequest.java:94)
at org.springframework.social.oauth2.OAuth2RequestInterceptor.intercept(
OAuth2RequestInterceptor.java:45)
at org.springframework.http.client.InterceptingClientHttpRequest$Request
Execution.execute(InterceptingClientHttpRequest.java:84)
at org.springframework.http.client.InterceptingClientHttpRequest.execute
Internal(InterceptingClientHttpRequest.java:69)
at org.springframework.http.client.AbstractBufferingClientHttpRequest.ex
ecuteInternal(AbstractBufferingClientHttpRequest.java:48)
at org.springframework.http.client.AbstractClientHttpRequest.execute(Abs
tractClientHttpRequest.java:53)
at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.ja
va:569)
at org.springframework.web.client.RestTemplate.execute(RestTemplate.java
:530)
at org.springframework.web.client.RestTemplate.getForObject(RestTemplate
.java:237)
at org.springframework.social.google.api.impl.AbstractGoogleApiOperation
s.getEntity(AbstractGoogleApiOperations.java:50)
at org.springframework.social.google.api.plus.impl.PlusTemplate.getPerso
n(PlusTemplate.java:105)
at org.springframework.social.google.api.plus.impl.PlusTemplate.getGoogl
eProfile(PlusTemplate.java:110)
at org.springframework.social.google.connect.GoogleAdapter.fetchUserProf
ile(GoogleAdapter.java:51)
at org.springframework.social.google.connect.GoogleAdapter.fetchUserProf
ile(GoogleAdapter.java:31)
at org.springframework.social.google.conneleConnectionFactory.extractPro
viderUserId(GoogleConnectionFactory.java:37)
at org.springframework.social.connect.support.OAuth2ConnectionFactory.cr
eateConnection(OAuth2ConnectionFactory.java:91)
at com.espn.gnow.controller.AddCredentials.addCredentials(AddCredentials
.java:60)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.
java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAcces
sorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
at org.springframework.web.method.support.InvocableHandlerMethod.doInvok
e(InvocableHandlerMethod.java:221)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeF
orRequest(InvocableHandlerMethod.java:137)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocabl
eHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:110)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingH
andlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:776)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingH
andlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:705)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapt
er.handle(AbstractHandlerMethodAdapter.java:85)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(Dispatch
erServlet.java:959)
at org.springframework.web.servlet.DispatcherServlet.doService(Dispatche
rServlet.java:893)
at org.springframework.web.servlet.FrameworkServlet.processRequest(Frame
workServlet.java:966)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServl
et.java:857)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:618)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkSer
vlet.java:842)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:725)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(Appl
icationFilterChain.java:291)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationF
ilterChain.java:206)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52
)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(Appl
icationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationF
ilterChain.java:206)
at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInterna
l(HiddenHttpMethodFilter.java:77)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerR
equestFilter.java:107)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(Appl
icationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationF
ilterChain.java:206)
at org.springframework.web.filter.CharacterEncodingFilter.doFilterIntern
al(CharacterEncodingFilter.java:85)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerR
equestFilter.java:107)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(Appl
icationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationF
ilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperV
alve.java:219)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextV
alve.java:106)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(Authentica
torBase.java:501)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.j
ava:142)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.j
ava:79)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineVal
ve.java:88)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.jav
a:516)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp
11Processor.java:1086)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(
AbstractProtocol.java:659)
at org.apache.coyote.http11.Http11NioProtocol$Http11Connectior.process(H
ttp11NioProtocol.java:223)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpo
int.java:1558)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoin
t.java:1515)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.
java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor
.java:617)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskTh
read.java:61)
at java.lang.Thread.run(Thread.java:745)

The documentation states that the connection must happen over https so I added a self signed certificate but to no avail.

I saw that there's another ticket on similar lines :

but I couldn't really understand the fix mentioned there... Please provide any pointers for fixing this...

@mlaccetti

mlaccetti commented May 6, 2015

Ensure you are using the Apache HttpClient 4.3.x library, not 4.4.x.

  • 👍 1 reaction
  • 👀 1 reaction

Sorry, something went wrong.

@mlaccetti

No branches or pull requests

@mlaccetti

  • Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
  • Advertising & Talent Reach devs & technologists worldwide about your product, service or employer brand
  • OverflowAI GenAI features for Teams
  • OverflowAPI Train & fine-tune LLMs
  • Labs The future of collective knowledge sharing
  • About the company Visit the blog

Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Get early access and see previews of new features.

Injecting a classpath resource into a Spring 3 bean

There is a property of type Resource in my Spring 3 bean that should be injected with a reference to a file in the classpath. I use the @Value annotation as below to hopefully achieve this.

But the property is always null. I have confirmed that the sql file has been deployed in the maven target directory (it is at target/classes/abc/student/test.sql).

The closest solutions that I could google were this and this which detail the xml way whereas I am interested in doing this using annotations.

Appreciate any pointers on what could be wrong here.

  • dependency-injection

Community's user avatar

2 Answers 2

If it's going to be hard-coded like that, then just

Otherwise, what you're really after is

and I believe that in injecting the property value, the correct PropertyEditor will be applied.

Ryan Stewart's user avatar

  • 1 Agreed - see stackoverflow.com/questions/6392406/… –  sourcedelica Commented Aug 11, 2011 at 2:35
  • Thank you for your replies. Both the solutions worked. I preferred the @Value approach as it permits no dependency on Spring classes from my code. –  Babu Subburathinam Commented Aug 11, 2011 at 4:30
  • 2 You do know that @Value is a spring class? –  Wes Commented Sep 22, 2017 at 14:50

If you don't want to specify a property then this should work

deFreitas's user avatar

Your Answer

Reminder: Answers generated by artificial intelligence tools are not allowed on Stack Overflow. Learn more

Sign up or log in

Post as a guest.

Required, but never shown

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy .

Not the answer you're looking for? Browse other questions tagged java spring dependency-injection or ask your own question .

  • Featured on Meta
  • Upcoming initiatives on Stack Overflow and across the Stack Exchange network...
  • Announcing a change to the data-dump process

Hot Network Questions

  • What's the frequency level of 時々?
  • How can dragons breathe in space?
  • Simple CLI based Mastermind clone in C
  • AmE: I never found the right one
  • Can one be restricted from carrying a gun on the metro in New York city?
  • Why is JavaScript executing callbacks in a for-loop so fast the first time?
  • How do I paste bash commands that contain sudo into a gnome-terminal?
  • Is every Boolean algebra a subalgebra of a free one?
  • How to Derive the Time Evolution Equation for Quantum Phase?
  • Do we ever see the dangers of violating the Prime Directive?
  • Why "praemiīs mē dōnant" and not "praemia mihi donant"?
  • Why does MoleculeModify only accept a single modification?
  • Why does this 4-week Treasury bill that I bought have a 17-week term and a much earlier issue date?
  • Pluto has smooth ice plains, almost like lunar maria. Where did the heat come from to melt all that ice?
  • bootstrapping a confidence interval with unbalanced data
  • Uniqueness results that follow from CH
  • Would it be possible to generate data from real data in medical research?
  • P-MOSFET always conducting
  • Has any US president ever endorsed Trump for US presidency?
  • N-Mos failing short on my PCB
  • Why would these two populations be genetically compatible?
  • All QFTs are Finite
  • Integer solutions for a simple cubic
  • Number of leaves in complete binary tree

spring resource annotation classpath

IMAGES

  1. spring resource annotation properties

    spring resource annotation classpath

  2. Spring Annotations Configuration

    spring resource annotation classpath

  3. Spring Annotation Based Configuration

    spring resource annotation classpath

  4. Common Spring annotations

    spring resource annotation classpath

  5. Spring Boot @SpringBootApplication, SpringApplication Class

    spring resource annotation classpath

  6. Spring @Resource Annotation Example

    spring resource annotation classpath

VIDEO

  1. 3 ways to autowire multiple interface implementations in spring boot

  2. 03-3 Spring Boot Application Annotation

  3. How to create custom annotations in Spring Boot

  4. Spring @Bean Annotation Examples

  5. 49.@Required annotation in Spring

  6. 21. @Required annotation in Spring

COMMENTS

  1. Access a File from the Classpath using Spring

    2.1. Manually. For accessing a resource from the classpath, we can simply use ClassPathResource: return new ClassPathResource ( "data/employees.dat" ); By default, ClassPathResource removes some boilerplate by selecting between the thread's context classloader and the default system classloader.

  2. Resources :: Spring Framework

    Spring Framework Resources is a comprehensive guide to the various types of resources that can be used in Spring applications, such as classpath, file system, URL, and byte array resources. It also explains how to access, manipulate, and customize resources using the Resource interface and its implementations. Learn how to use resources effectively with Spring Framework Resources.

  3. Load a Resource as a String in Spring

    Spring helps us find and read a resource using the resource loader, which decides which Resource implementation to pick depending on the path provided. The Resource is effectively a way of accessing the content of the resource, rather than the content itself. Let's see some ways to acquire a Resource instance for resources on the classpath.

  4. Java Spring

    Here, we are using @PropertySource annotation with a value of classpath:discounts.properties in the Java config class. The classpath: prefix tells the Spring to search for the discounts.properties file in the Java classpath. Once we define the @PropertySource annotation to load the properties file, as we discussed earlier, we also need to ...

  5. Mastering Resource Handling in Spring

    Resource handling is an integral part of any real-world application, whether it is about loading a properties file, reading a dataset, or handling configurations. Spring Framework provides various ...

  6. java

    Try to determine the starting path in ClassPath, Resource resource = new ClassPathResource("" or File.seperator); resource.getFile().getAbsolutePath(); So that you can give the appropriate value inside new CPR() based on above result -

  7. Spring Read Classpath Resource using @Value

    In this Java Spring Framework tutorial, we learn how to use @Value annotation to read classpath resource files located in the resources folder in your Spring application project. For example, we have a text file located at /src/main/resources/data.json in the Spring application project. Next step, we implement a new class named ResourceService ...

  8. Spring @ImportResource Annotation Example

    Spring provides a @ImportResource annotation that is used to load beans from an applicationContext.xml file into an Application Context. @ImportResource ( { "classpath*:applicationContext.xml" }) In this example, we are creating a simple message-processing spring boot application. Here we are sending a message using different services like ...

  9. Read a File from Resources in Spring Boot

    Learn to read a file from the '/resources' folder in a Spring boot application using ClassPathResource class, ResourceLoader interface or @Value annotation. @Autowired private ResourceLoader resourceLoader; public void method(){ Resource resource = resourceLoader.getResource("classpath:filename.txt"); File file = resource.getFile()); //...

  10. Working with Resources in Spring

    We may also specify a URL as a resource path. Below are the ways to load external resources: Load resource from the application root folder. To load a file from the application folder, use this. Resource resource = resourceLoader.getResource("file:data.txt"); Load resource from classpath. To load a file from the classpath, use this.

  11. Spring ClassPathResource tutorial

    Spring is a popular Java application framework for creating enterprise applications. Spring ClassPathResource. ClassPathResource allows to obtain resources from a Java classpath. Spring ClassPathResource example. The application reads text data from a file located in the Java classpath.

  12. Wiring in Spring: @Autowired, @Resource and @Inject

    @Resource private File defaultFile; Then we run the test again. The test will still pass because if the @Resource annotation doesn't receive a bean name as an attribute value, the Spring Framework will proceed with the next level of precedence, match-by-type, in order to try resolve the dependency.. 2.1.3. Match by Qualifier. To demonstrate the match-by-qualifier execution path, the ...

  13. Working With Resources in Spring

    Resource resource = resourceLoader.getResource("classpath:data.txt"); Load resource from the filesystem To load a file from filesystem outside the application folder, use the below template:

  14. Spring Boot

    The diagram below shows Spring Boot as a point of focus on the larger Spring ecosystem. It presents a small surface area for users to approach and extract value from the rest of Spring: The primary goals of Spring Boot are: To provide a radically faster and widely accessible 'getting started' experience for all Spring development.

  15. PDF Geothermal Resource Conceptual Models Using Surface Exploration Data

    This paper briefly outlines three approaches commonly used to use data to target wells and assess resource capacity in conventional permeable geothermal reservoirs from 120 to 350°C at the exploration stage of a prospect. It promotes a conceptual model approach as a plausible best practice, recognizing that no practice is best in every context.

  16. N Rishi

    • Developed the persistence layer using Hibernate Framework, created the POJO objects and mapped using Hibernate annotations and Transaction Management.

  17. Host name 'www.googleapis.com' does not match the certificate subject

    Resources Topics. AI DevOps ... as per the google now api documentations and the current code uses google oauth api client and we thought of using spring-social for establishing the oauth2 connection from the controller. the reason we can't use the google apis is that it is tightly coupled with the google data store and we want to move away ...

  18. Java Spring

    And make sure you are adding the resources directory correctly (adding /src/main/resources/ into the classpath). Note that Resource have a method to get a java.io.File so you can also use: Resource resource = new ClassPathResource("storedProcedures.sql"); FileReader fr = new FileReader(resource.getFile()); edited May 23, 2017 at 12:17.

  19. Injecting a classpath resource into a Spring 3 bean

    There is a property of type Resource in my Spring 3 bean that should be injected with a reference to a file in the classpath. I use the @Value annotation as below to hopefully achieve this. I use the @Value annotation as below to hopefully achieve this.