- 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
![](http://academicwritinghelp.pw/777/templates/cheerup1/res/banner1.gif)
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.
![spring resource annotation classpath Output](https://media.geeksforgeeks.org/wp-content/uploads/20220911175620/Out1.jpg)
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.
![spring resource annotation classpath Output](https://media.geeksforgeeks.org/wp-content/uploads/20220911181022/out2.jpg)
Output – Resource interface
The final project structure will be as follows:
![spring resource annotation classpath project structure](https://media.geeksforgeeks.org/wp-content/uploads/20220911181544/PS.jpg)
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.
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 😊
Spring Framework Guru
Working with resources in spring.
![spring resource annotation classpath Spring Framework Guru](https://springframework.guru/wp-content/uploads/2015/03/Banner560x292_05web.jpg)
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
About SFG Contributor
Staff writer account for Spring Framework Guru
You May Also Like
![spring resource annotation classpath JWT Token Authentication in Spring Boot Microservices](https://springframework.guru/wp-content/uploads/2021/02/Spring-Security-Core-02-410x308.jpg)
JWT Token Authentication in Spring Boot Microservices
![spring resource annotation classpath Spring Framework Guru](https://springframework.guru/wp-content/uploads/2017/07/Banner560x292_08Web-410x292.jpg)
Hikari Configuration for MySQL in Spring Boot 2
![spring resource annotation classpath Spring Framework Guru](https://springframework.guru/wp-content/uploads/2015/03/Banner560x292_01web-410x292.jpg)
Database Migration with Flyway
![spring resource annotation classpath Spring Framework 6](https://springframework.guru/wp-content/uploads/2017/07/Spring-Cloud-Blog-greenSweb-410x292.jpg)
Getting Ready for Spring Framework 6
![spring resource annotation classpath Using Filters in Spring Web Applications](https://springframework.guru/wp-content/uploads/2017/07/NewBannerBOOTSWeb-410x292.jpg)
Using Filters in Spring Web Applications
![spring resource annotation classpath Bootstrapping Data in Spring Boot](https://springframework.guru/wp-content/uploads/2017/07/NewBannerBOOTSWeb-410x292.jpg)
Bootstrapping Data in Spring Boot
![spring resource annotation classpath Hikari Connection Pool](https://springframework.guru/wp-content/uploads/2021/03/microservices.jpg)
Eureka Service Registry
![spring resource annotation classpath Spring Framework Guru](https://springframework.guru/wp-content/uploads/2015/03/Banner560x292_05web-410x292.jpg)
Scheduling in Spring Boot
![spring resource annotation classpath Spring for Apache Kafka](https://springframework.guru/wp-content/uploads/2015/03/Banner560x292_06web-410x292.jpg)
Spring for Apache Kafka
Spring retry.
![spring resource annotation classpath Spring Boot CLI](https://springframework.guru/wp-content/uploads/2017/07/NewBannerBOOTSWeb-410x292.jpg)
Spring Boot CLI
![spring resource annotation classpath Spring Framework Guru](https://springframework.guru/wp-content/uploads/2017/07/Banner560x292_09web-410x308.jpg)
Actuator in Spring Boot
![spring resource annotation classpath Internationalization with Spring Boot](https://springframework.guru/wp-content/uploads/2015/03/Banner560x292_03web-410x292.jpg)
Internationalization with Spring Boot
One-to-one relationship in jpa.
![spring resource annotation classpath Spring Framework Guru](https://springframework.guru/wp-content/uploads/2015/03/Banner560x292_06aweb-410x292.jpg)
The @RequestBody Annotation
![spring resource annotation classpath Learn Spring](https://springframework.guru/wp-content/uploads/2015/03/Banner560x292_02.png)
Spring BeanFactory vs ApplicationContext
![spring resource annotation classpath MySQL Stored Procedures with Spring Boot](https://springframework.guru/wp-content/uploads/2015/03/Banner560x292_03web-410x292.jpg)
MySQL Stored Procedures with Spring Boot
![spring resource annotation classpath Spring Framework Guru](https://springframework.guru/wp-content/uploads/2015/03/Banner560x292_04web-410x292.jpg)
Bean Validation in Spring Boot
Spring state machine.
![spring resource annotation classpath Exception Handling in Spring Boot REST API](https://springframework.guru/wp-content/uploads/2018/07/Testing-Spring-Boot03c-email.jpg)
Exception Handling in Spring Boot REST API
![spring resource annotation classpath Spring Boot Pagination](https://springframework.guru/wp-content/uploads/2015/03/Banner560x292_02web-410x292.jpg)
Spring Boot Pagination
Spring rest docs, using mapstruct with project lombok, argumentcaptor in mockito.
![spring resource annotation classpath Spring Framework Guru](https://springframework.guru/wp-content/uploads/2015/03/Banner560x292_05aweb-410x292.jpg)
Reading External Configuration Properties in Spring
Api gateway with spring cloud.
![spring resource annotation classpath Testing Spring Boot RESTful Services](https://springframework.guru/wp-content/uploads/2017/07/Testing-Spring-Boot03cweb-410x308.jpg)
Testing Spring Boot RESTful Services
![spring resource annotation classpath Caching in Spring RESTful Service: Part 2 - Cache Eviction](https://springframework.guru/wp-content/uploads/2017/07/NewBannerBOOTSWeb-410x292.jpg)
Caching in Spring RESTful Service: Part 2 – Cache Eviction
Spring boot messaging with rabbitmq.
![spring resource annotation classpath Caching in Spring Boot RESTful Service: Part 1](https://springframework.guru/wp-content/uploads/2017/07/NewBannerBOOTSWeb-410x292.jpg)
Caching in Spring Boot RESTful Service: Part 1
![spring resource annotation classpath Spring Framework Guru](https://springframework.guru/wp-content/uploads/2019/05/Banner560x292_08Web-410x292.jpg)
Implementing HTTP Basic Authentication in a Spring Boot REST API
![spring resource annotation classpath Immutable Property Binding](https://springframework.guru/wp-content/uploads/2017/07/NewBannerBOOTSWeb-410x292.jpg)
Immutable Property Binding
![spring resource annotation classpath Java Bean Properties Binding](https://springframework.guru/wp-content/uploads/2017/07/NewBannerBOOTSWeb-410x292.jpg)
Java Bean Properties Binding
External configuration data in spring.
![spring resource annotation classpath Spring Data JPA @Query](https://springframework.guru/wp-content/uploads/2017/07/Spring-5ver02bweb-410x308.jpg)
Spring Data JPA @Query
Configuring mysql with circleci.
![spring resource annotation classpath Fabric8 Docker Maven Plugin](https://springframework.guru/wp-content/uploads/2020/05/DocerNEW01-410x308.png)
Fabric8 Docker Maven Plugin
![spring resource annotation classpath Feign REST Client for Spring Application](https://springframework.guru/wp-content/uploads/2017/07/Banner560x292_08bw-410x292.jpg)
Feign REST Client for Spring Application
![spring resource annotation classpath Docker Hub for Spring Boot](https://springframework.guru/wp-content/uploads/2020/05/DocerNEW01-410x308.png)
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.
![spring resource annotation classpath Consul Miniseries: Spring Boot Application and Consul Integration Part 1](https://springframework.guru/wp-content/uploads/2018/08/Spring-Cloud-Blog-greenS.png)
Consul Miniseries: Spring Boot Application and Consul Integration Part 1
![spring resource annotation classpath Why You Should be Using Spring Boot Docker Layers](https://springframework.guru/wp-content/uploads/2018/06/NewBannerBOOTSWeb-410x292.jpg)
Why You Should be Using Spring Boot Docker Layers
![spring resource annotation classpath Spring Bean Scopes](https://springframework.guru/wp-content/uploads/2017/07/Banner560x292_08bw-410x292.jpg)
Spring Bean Scopes
Debug your code in intellij idea, stay at home, learn from home with 6 free online courses.
![spring resource annotation classpath What is the best UI to Use with Spring Boot?](https://springframework.guru/wp-content/uploads/2017/07/NewBannerBOOTSWeb-410x292.jpg)
What is the best UI to Use with Spring Boot?
![spring resource annotation classpath Best Practices for Dependency Injection with Spring](https://springframework.guru/wp-content/uploads/2015/03/Banner560x292_03web-410x292.jpg)
Best Practices for Dependency Injection with Spring
![spring resource annotation classpath Should I Use Spring REST Docs or OpenAPI?](https://springframework.guru/wp-content/uploads/2019/11/OPENapi03email-410x308.jpg)
Should I Use Spring REST Docs or OpenAPI?
Spring boot with lombok: part 1.
![spring resource annotation classpath Spring Framework Guru](https://springframework.guru/wp-content/uploads/2019/05/Banner.txt.png)
Using Project Lombok with Gradle
Spring bean lifecycle, spring profiles, spring bean definition inheritance, autowiring in spring.
![spring resource annotation classpath spring boot](https://springframework.guru/wp-content/uploads/2015/06/NewBannerBOOTS_2.png)
What is New in Spring Boot 2.2?
![spring resource annotation classpath Using Ehcache 3 in Spring Boot](https://springframework.guru/wp-content/uploads/2018/06/NewBannerBOOTSWeb-410x292.jpg)
Using Ehcache 3 in Spring Boot
How to configure multiple data sources in a spring boot application.
![spring resource annotation classpath Using RestTemplate with Apaches HttpClient](https://springframework.guru/wp-content/uploads/2015/03/Banner560x292_06web-410x292.jpg)
Using RestTemplate with Apaches HttpClient
![spring resource annotation classpath Using RestTemplate in Spring](https://springframework.guru/wp-content/uploads/2017/07/Banner560x292_08bw-410x292.jpg)
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.
![spring resource annotation classpath Hibernate Show SQL](https://springframework.guru/wp-content/uploads/2018/06/NewBannerBOOTSWeb-410x292.jpg)
Hibernate Show SQL
![spring resource annotation classpath Spring Component Scan](https://springframework.guru/wp-content/uploads/2018/06/NewBannerBOOTSWeb-410x292.jpg)
Spring Component Scan
![spring resource annotation classpath Using CircleCI to Build Spring Boot Microservices](https://springframework.guru/wp-content/uploads/2018/06/NewBannerBOOTSWeb-410x292.jpg)
Using CircleCI to Build Spring Boot Microservices
Spring framework annotations.
![spring resource annotation classpath Using JdbcTemplate with Spring Boot and Thymeleaf](https://springframework.guru/wp-content/uploads/2018/06/NewBannerBOOTSWeb-410x292.jpg)
Using JdbcTemplate with Spring Boot and Thymeleaf
Using the spring @requestmapping annotation.
![spring resource annotation classpath Spring Data MongoDB with Reactive MongoDB](https://springframework.guru/wp-content/uploads/2017/07/Spring-5ver02bweb-410x308.jpg)
Spring Data MongoDB with Reactive MongoDB
![spring resource annotation classpath Spring Boot with Embedded MongoDB](https://springframework.guru/wp-content/uploads/2018/06/NewBannerBOOTSWeb-410x292.jpg)
Spring Boot with Embedded MongoDB
![spring resource annotation classpath Spring Web Reactive](https://springframework.guru/wp-content/uploads/2017/07/Spring-5ver02bweb-410x308.jpg)
![](http://academicwritinghelp.pw/777/templates/cheerup1/res/banner1.gif)
Spring Web Reactive
![spring resource annotation classpath What are Reactive Streams in Java?](https://springframework.guru/wp-content/uploads/2017/07/ReactiveIsComing2NewSmall-web.jpg)
What are Reactive Streams in Java?
![spring resource annotation classpath Spring Framework 5](https://springframework.guru/wp-content/uploads/2017/06/WinterIsComing2NewSmall.png)
What’s new in Spring Framework 5?
![spring resource annotation classpath Spring Boot RESTful API Documentation with Swagger 2](https://springframework.guru/wp-content/uploads/2018/06/NewBannerBOOTSWeb-410x292.jpg)
Spring Boot RESTful API Documentation with Swagger 2
![spring resource annotation classpath Mockito Mock vs Spy in Spring Boot Tests](https://springframework.guru/wp-content/uploads/2017/07/Banner560x292_08bw-410x292.jpg)
Mockito Mock vs Spy in Spring Boot Tests
![spring resource annotation classpath Spring Boot Mongo DB Example Application](https://springframework.guru/wp-content/uploads/2018/06/NewBannerBOOTSWeb-410x292.jpg)
Spring Boot Mongo DB Example Application
![spring resource annotation classpath Configuring Spring Boot for MariaDB](https://springframework.guru/wp-content/uploads/2018/06/NewBannerBOOTSWeb-410x292.jpg)
Configuring Spring Boot for MariaDB
Spring boot web application, part 6 – spring security with dao authentication provider.
![spring resource annotation classpath Configuring Spring Boot for MongoDB](https://springframework.guru/wp-content/uploads/2018/06/NewBannerBOOTSWeb-410x292.jpg)
Configuring Spring Boot for MongoDB
![spring resource annotation classpath Spring Boot Web Application, Part 5 - Spring Security](https://springframework.guru/wp-content/uploads/2018/06/NewBannerBOOTSWeb-410x292.jpg)
Spring Boot Web Application, Part 5 – Spring Security
![spring resource annotation classpath Chuck Norris for Spring Boot Actuator](https://springframework.guru/wp-content/uploads/2016/12/ThumbActuator.png)
Chuck Norris for Spring Boot Actuator
Testing spring mvc with spring boot 1.4: part 1, running spring boot in a docker container.
![spring resource annotation classpath Jackson Dependency Issue in Spring Boot with Maven Build](https://springframework.guru/wp-content/uploads/2018/06/NewBannerBOOTSWeb-410x292.jpg)
Jackson Dependency Issue in Spring Boot with Maven Build
![spring resource annotation classpath Using YAML in Spring Boot to Configure Logback](https://springframework.guru/wp-content/uploads/2018/06/NewBannerBOOTSWeb-410x292.jpg)
Using YAML in Spring Boot to Configure Logback
![spring resource annotation classpath Using Logback with Spring Boot](https://springframework.guru/wp-content/uploads/2018/06/NewBannerBOOTSWeb-410x292.jpg)
Using Logback with Spring Boot
![spring resource annotation classpath Using Log4J 2 with Spring Boot](https://springframework.guru/wp-content/uploads/2018/06/NewBannerBOOTSWeb-410x292.jpg)
Using Log4J 2 with Spring Boot
Fixing nouniquebeandefinitionexception exceptions, samy is my hero and hacking the magic of spring boot.
![spring resource annotation classpath 2015 Year in Review](https://springframework.guru/wp-content/uploads/2015/03/Banner560x292_03.png)
2015 Year in Review
![spring resource annotation classpath Configuring Spring Boot for PostgreSQL](https://springframework.guru/wp-content/uploads/2018/06/NewBannerBOOTSWeb-410x292.jpg)
Configuring Spring Boot for PostgreSQL
![spring resource annotation classpath Embedded JPA Entities Under Spring Boot and Hibernate Naming](https://springframework.guru/wp-content/uploads/2018/06/NewBannerBOOTSWeb-410x292.jpg)
Embedded JPA Entities Under Spring Boot and Hibernate Naming
![spring resource annotation classpath Spring Boot Developer Tools](https://springframework.guru/wp-content/uploads/2018/06/NewBannerBOOTSWeb-410x292.jpg)
Spring Boot Developer Tools
Spring beanfactoryaware interface.
![spring resource annotation classpath Spring BeanNameAware Interface](https://springframework.guru/wp-content/uploads/2015/03/Banner560x292_03web-410x292.jpg)
Spring BeanNameAware Interface
Displaying list of objects in table using thymeleaf.
![spring resource annotation classpath Using H2 and Oracle with Spring Boot](https://springframework.guru/wp-content/uploads/2018/06/NewBannerBOOTSWeb-410x292.jpg)
Using H2 and Oracle with Spring Boot
![spring resource annotation classpath Configuring Spring Boot for Oracle](https://springframework.guru/wp-content/uploads/2018/06/NewBannerBOOTSWeb-410x292.jpg)
Configuring Spring Boot for Oracle
![spring resource annotation classpath Spring Boot Web Application - Part 4 - Spring MVC](https://springframework.guru/wp-content/uploads/2018/06/NewBannerBOOTSWeb-410x292.jpg)
Spring Boot Web Application – Part 4 – Spring MVC
![spring resource annotation classpath Configuring Spring Boot for MySQL](https://springframework.guru/wp-content/uploads/2018/06/NewBannerBOOTSWeb-410x292.jpg)
Configuring Spring Boot for MySQL
![spring resource annotation classpath Spring Boot Example of Spring Integration and ActiveMQ](https://springframework.guru/wp-content/themes/verko/includes/assets/images/post-formats/big/standard.jpg)
Spring Boot Example of Spring Integration and ActiveMQ
How do i become a java web developer.
![spring resource annotation classpath Spring Boot Web Application - Part 3 - Spring Data JPA](https://springframework.guru/wp-content/uploads/2018/06/NewBannerBOOTSWeb-410x292.jpg)
Spring Boot Web Application – Part 3 – Spring Data JPA
![spring resource annotation classpath Spring Boot Web Application - Part 2 - Using ThymeLeaf](https://springframework.guru/wp-content/uploads/2018/06/NewBannerBOOTSWeb-410x292.jpg)
Spring Boot Web Application – Part 2 – Using ThymeLeaf
![spring resource annotation classpath Spring Boot Web Application - Part 1 - Spring Initializr](https://springframework.guru/wp-content/uploads/2018/06/NewBannerBOOTSWeb-410x292.jpg)
Spring Boot Web Application – Part 1 – Spring Initializr
![spring resource annotation classpath Using the H2 Database Console in Spring Boot with Spring Security](https://springframework.guru/wp-content/uploads/2015/03/Banner560x292_03web-410x292.jpg)
Using the H2 Database Console in Spring Boot with Spring Security
Running code on spring boot startup, integration testing with spring and junit.
![spring resource annotation classpath polyglot programming](https://springframework.guru/wp-content/uploads/2015/05/o-mike-myers-officially-signs-on-for-austin-powers-4.jpg)
Polyglot Programming in Spring
![spring resource annotation classpath Using Spring Integration Futures](https://springframework.guru/wp-content/uploads/2015/03/Banner560x292_03web-410x292.jpg)
Using Spring Integration Futures
Using the spring framework for enterprise application development.
![spring resource annotation classpath Testing Spring Integration Gateways](https://springframework.guru/wp-content/uploads/2015/03/Banner560x292_03web-410x292.jpg)
Testing Spring Integration Gateways
![spring resource annotation classpath Introduction to Spring Expression Language (SpEL)](https://springframework.guru/wp-content/uploads/2015/03/Banner560x292_03web-410x292.jpg)
Introduction to Spring Expression Language (SpEL)
![spring resource annotation classpath Hello World Using Spring Integration](https://springframework.guru/wp-content/uploads/2015/03/Banner560x292_03web-410x292.jpg)
Hello World Using Spring Integration
![spring resource annotation classpath Creating Spring Beans](https://springframework.guru/wp-content/uploads/2015/03/Banner560x292_03web-410x292.jpg)
Creating Spring Beans
![spring resource annotation classpath Dependency Injection Example Using Spring](https://springframework.guru/wp-content/uploads/2015/03/Banner560x292_03web-410x292.jpg)
Dependency Injection Example Using Spring
![spring resource annotation classpath Hello World With Spring 4](https://springframework.guru/wp-content/uploads/2015/03/Banner560x292_02web-410x292.jpg)
Hello World With Spring 4
Getting started with spring boot.
![spring resource annotation classpath What's all the fuss about Java Lambdas?](https://springframework.guru/wp-content/uploads/2015/02/lambda200x200.png)
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 .
- Send Message
- Core Java Tutorials
- Java EE Tutorials
- Java Swing Tutorials
- Spring Framework Tutorials
- Unit Testing
- Build Tools
- Misc Tutorials
- InjectFileResourceDataExample.java
- InjectResourceDataExample.java
- InjectResourceExample.java
- InjectUrlResourceDataExample.java
- myResource.txt
- PyQt5 ebook
- Tkinter ebook
- SQLite Python
- wxPython ebook
- Windows API ebook
- Java Swing ebook
- Java games ebook
- MySQL Java ebook
Spring ClassPathResource tutorial
last modified October 18, 2023
Spring ClassPathResource tutorial shows how to read resources with a ClassPathResource in a Spring application.
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.
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.
In the my-beans.xml file, we configure the readWordsService bean. It becomes a Spring managed bean.
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 ReadWordsService reads the words into a list and returns the list to the client.
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.
List all Spring tutorials .
![ezoic spring resource annotation classpath](https://go.ezodn.com/utilcave_com/ezoic.png)
Properties with Spring and Spring Boot
Last updated: January 8, 2024
- Spring Boot
- Spring Core Basics
![spring resource annotation classpath announcement - icon](https://www.baeldung.com/wp-content/uploads/2022/04/announcement-icon.png)
The entirely new V2 of my flagship REST With Spring course is out:
>> REST With Spring Boot
This has been my first and most popular course, so it's been cool releasing this all-new material here.
Now that the new version of REST With Spring - “REST With Spring Boot” is finally out, the current price will be available until the 22nd of June , after which it will permanently increase by 50$
Azure Spring Apps is a fully managed service from Microsoft (built in collaboration with VMware), focused on building and deploying Spring Boot applications on Azure Cloud without worrying about Kubernetes.
The Enterprise plan comes with some interesting features, such as commercial Spring runtime support, a 99.95% SLA and some deep discounts (up to 47%) when you are ready for production.
>> Learn more and deploy your first Spring Boot app to Azure.
And, you can participate in a very quick (1 minute) paid user research from the Java on Azure product team.
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
A quick guide to materially improve your tests with Junit 5:
Do JSON right with Jackson
Download the E-book
Get the most out of the Apache HTTP Client
Get Started with Apache Maven:
Get started with Spring and Spring Boot, through the reference Learn Spring course:
>> LEARN SPRING
Building a REST API with 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
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
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.
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
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
Creating PDFs is actually surprisingly hard. When we first tried, none of the existing PDF libraries met our needs. So we made DocRaptor for ourselves and later launched it as one of the first HTML-to-PDF APIs.
We think DocRaptor is the fastest and most scalable way to make PDFs , especially high-quality or complex PDFs. And as developers ourselves, we love good documentation, no-account trial keys, and an easy setup process.
>> Try DocRaptor's HTML-to-PDF Java Client (No Signup Required)
Get started with Spring Boot and with core Spring, through the Learn Spring course:
>> CHECK OUT THE COURSE
1. Overview
This tutorial will show how to set up and use properties in Spring via Java configuration and @PropertySource.
We’ll also see how properties work in Spring Boot.
Further reading:
Spring expression language guide, configure a spring boot web application, guide to @configurationproperties in spring boot, 2. register a properties file via annotations.
Spring 3.1 also introduces the new @PropertySource annotation as a convenient mechanism for adding property sources to the environment.
We can use this annotation in conjunction with the @Configuration annotation:
Another very useful way to register a new properties file is using a placeholder, which allows us to dynamically select the right file at runtime :
2.1. Defining Multiple Property Locations
The @PropertySource annotation is repeatable according to Java 8 conventions . Therefore, if we’re using Java 8 or higher, we can use this annotation to define multiple property locations:
Of course, we can also use the @PropertySources annotation and specify an array of @PropertySource . This works in any supported Java version, not just in Java 8 or higher:
In either case, it’s worth noting that in the event of a property name collision, the last source read takes precedence.
3. Using/Injecting Properties
Injecting a property with the @Value annotation is straightforward:
We can also specify a default value for the property:
The new PropertySourcesPlaceholderConfigurer added in Spring 3.1 resolve ${…} placeholders within bean definition property values and @Value annotations .
Finally, we can obtain the value of a property using the Environment API :
4. Properties With Spring Boot
Before we go into more advanced configuration options for properties, let’s spend some time looking at the new properties support in Spring Boot.
Generally speaking, this new support involves less configuration compared to standard Spring , which is of course one of the main goals of Boot.
4.1. application.properties: the Default Property File
Boot applies its typical convention over configuration approach to property files. This means that we can simply put an application.properties file in our src/main/resources directory, and it will be auto-detected . We can then inject any loaded properties from it as normal.
So, by using this default file, we don’t have to explicitly register a PropertySource or even provide a path to a property file.
We can also configure a different file at runtime if we need to, using an environment property:
As of Spring Boot 2.3 , we can also specify wildcard locations for configuration files .
For example, we can set the spring.config.location property to config/*/ :
This way, Spring Boot will look for configuration files matching the config/*/ directory pattern outside of our jar file. This comes in handy when we have multiple sources of configuration properties.
Since version 2.4.0 , Spring Boot supports using multi-document properties files , similarly as YAML does by design:
Note that for properties files, the three-dashes notation is preceded by a comment character ( # ).
4.2. Environment-Specific Properties File
If we need to target different environments, there’s a built-in mechanism for that in Boot.
We can simply define an application-environment.properties file in the src/main/resources directory, and then set a Spring profile with the same environment name.
For example, if we define a “staging” environment, that means we’ll have to define a staging profile and then application-staging.properties .
This env file will be loaded and will take precedence over the default property file. Note that the default file will still be loaded, it’s just that when there is a property collision, the environment-specific property file takes precedence.
4.3. Test-Specific Properties File
We might also have a requirement to use different property values when our application is under test.
Spring Boot handles this for us by looking in our src/test/resources directory during a test run . Again, default properties will still be injectable as normal but will be overridden by these if there is a collision.
4.4. The @TestPropertySource Annotation
If we need more granular control over test properties, then we can use the @TestPropertySource annotation.
This allows us to set test properties for a specific test context, taking precedence over the default property sources:
If we don’t want to use a file, we can specify names and values directly:
We can also achieve a similar effect using the properties argument of the @SpringBootTest annotation:
4.5. Hierarchical Properties
If we have properties that are grouped together, we can make use of the @ConfigurationProperties annotation, which will map these property hierarchies into Java objects graphs.
Let’s take some properties used to configure a database connection:
And then let’s use the annotation to map them to a database object:
Spring Boot applies it’s convention over configuration approach again, automatically mapping between property names and their corresponding fields. All that we need to supply is the property prefix.
If you want to dig deeper into configuration properties, have a look at our in-depth article .
4.6. Alternative: YAML Files
Spring also supports YAML files.
All the same naming rules apply for test-specific, environment-specific, and default property files. The only difference is the file extension and a dependency on the SnakeYAML library being on our classpath.
YAML is particularly good for hierarchical property storage ; the following property file:
is synonymous with the following YAML file:
It’s also worth mentioning that YAML files do not support the @PropertySource annotation, so if we need to use this annotation, it would constrain us to using a properties file.
Another remarkable point is that in version 2.4.0 Spring Boot changed the way in which properties are loaded from multi-document YAML files. Previously, the order in which they were added was based on the profile activation order. With the new version, however, the framework follows the same ordering rules that we indicated earlier for .properties files; properties declared lower in the file will simply override those higher up.
Additionally, in this version profiles can no longer be activated from profile-specific documents, making the outcome clearer and more predictable.
4.7. Importing Additional Configuration Files
Prior to version 2.4.0, Spring Boot allowed including additional configuration files using the spring.config.location and spring.config.additional-location properties, but they had certain limitations. For instance, they had to be defined before starting the application (as environment or system properties, or using command-line arguments) as they were used early in the process.
In the mentioned version, we can use the spring.config.import property within the application.properties or application.yml file to easily include additional files. This property supports some interesting features:
- adding several files or directories
- the files can be loaded either from the classpath or from an external directory
- indicating if the startup process should fail if a file is not found, or if it’s an optional file
- importing extensionless files
Let’s see a valid example:
Note: here we formatted this property using line breaks just for clarity.
Spring will treat imports as a new document inserted immediately below the import declaration.
4.8. Properties From Command Line Arguments
Besides using files, we can pass properties directly on the command line:
We can also do this via system properties, which are provided before the -jar command rather than after it:
4.9. Properties From Environment Variables
Spring Boot will also detect environment variables, treating them as properties:
4.10. Randomization of Property Values
If we don’t want determinist property values, we can use RandomValuePropertySource to randomize the values of properties:
4.11. Additional Types of Property Sources
Spring Boot supports a multitude of property sources, implementing a well-thought-out ordering to allow sensible overriding. It’s worth consulting the official documentation , which goes further than the scope of this article.
5. Configuration Using Raw Beans — the PropertySourcesPlaceholderConfigurer
Besides the convenient methods of getting properties into Spring, we can also define and regiter the property configuration bean manually.
Working with the PropertySourcesPlaceholderConfigurer gives us full control over the configuration, with the downside of being more verbose and most of the time, unnecessary.
Let’s see how we can define this bean using Java configuration:
6. Properties in Parent-Child Contexts
This question comes up again and again: What happens when our web application has a parent and a child context ? The parent context may have some common core functionality and beans, and then one (or multiple) child contexts, maybe containing servlet-specific beans.
In that case, what’s the best way to define properties files and include them in these contexts? And how to best retrieve these properties from Spring?
We’ll give a simple breakdown.
If the file is defined in the Parent context :
- @Value works in Child context : YES
- @Value works in Parent context : YES
- environment.getProperty in Child context : YES
- environment.getProperty in Parent context : YES
If the file is defined in the Child context :
- @Value works in Parent context : NO
- environment.getProperty in Parent context : NO
7. Conclusion
This article showed several examples of working with properties and properties files in Spring.
As always, the entire code backing the article is available over 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.
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.
![spring resource annotation classpath Build your API with SPRING - book cover](https://www.baeldung.com/wp-content/uploads/2016/05/baeldung-rest-post-footer-main-1.2.0.jpg)
InfoQ Software Architects' Newsletter
A monthly overview of things you need to know as an architect or aspiring architect.
View an example
We protect your privacy.
Facilitating the Spread of Knowledge and Innovation in Professional Software Development
- English edition
- Chinese edition
- Japanese edition
- French edition
Back to login
Login with:
Don't have an infoq account, helpful links.
- About InfoQ
- InfoQ Editors
Write for InfoQ
- About C4Media
Choose your language
Special Memorial Day Sale with significant discounts of up to 60% off . Register now.
Special Summer Sale up to 60% off. Only 150 tickets available at this price.
Level up your software skills by uncovering the emerging trends you should focus on. Register now.
Your monthly guide to all the topics, technologies and techniques that every professional needs to know about. Subscribe for free.
InfoQ Homepage News Java News Roundup: JEPs Targeted for JDK 23, JHipster 8.5, Gradle 8.8, Spring AI 1.0-M1
Java News Roundup: JEPs Targeted for JDK 23, JHipster 8.5, Gradle 8.8, Spring AI 1.0-M1
Jun 03, 2024 11 min read
Michael Redlich
This week's Java roundup for May 27th, 2024 features news highlighting: four JEPs targeted for JDK 23, namely: JEP 482, Flexible Constructor Bodies (Second Preview), JEP 481, Scoped Values (Third Preview), JEP 480, Structured Concurrency (Third Preview) and JEP 471, Deprecate the Memory-Access Methods in Unsafe for Removal; and the releases of JHipster 8.5, Gradle 8.8 and Spring AI 1.0-M1.
After its review has concluded, JEP 482, Flexible Constructor Bodies (Second Preview) , has been promoted from Proposed to Target to Targeted for JDK 23. This JEP proposes a second round of preview and a name change to obtain feedback from the previous round of preview, namely JEP 447, Statements before super(...) (Preview) , delivered in JDK 22. This feature allows statements that do not reference an instance being created to appear before the this() or super() calls in a constructor; and preserve existing safety and initialization guarantees for constructors. Changes in this JEP include: a treatment of local classes; and a relaxation of the restriction that fields can not be accessed before an explicit constructor invocation to a requirement that fields can not be read before an explicit constructor invocation. Gavin Bierman , Consulting Member of Technical Staff at Oracle, has provided an initial specification of this JEP for the Java community to review and provide feedback.
After its review has concluded, JEP 481, Scoped Values (Third Preview) , has been promoted from Proposed to Target to Targeted for JDK 23. Formerly known as Extent-Local Variables (Incubator) , this JEP proposes a third preview, with one change, in order to gain additional experience and feedback from one round of incubation and two rounds of preview, namely: JEP 464, Scoped Values (Second Preview) , delivered in JDK 22; JEP 446, Scoped Values (Preview) , delivered in JDK 21; and JEP 429, Scoped Values (Incubator) , delivered in JDK 20. This feature enables sharing of immutable data within and across threads. This is preferred to thread-local variables, especially when using large numbers of virtual threads. The change in this feature is related to the operation parameter of the callWhere() method, defined in the ScopedValue class, is now a functional interface which allows the Java compiler to infer whether a checked exception might be thrown. With this change, the getWhere() method is no longer needed and has been removed.
After its review has concluded, JEP 480, Structured Concurrency (Third Preview) , has been promoted from Proposed to Target to Targeted for JDK 23. This JEP proposes a third preview, without change, in order to gain more feedback from the previous two rounds of preview, namely: JEP 462, Structured Concurrency (Second Preview) , delivered in JDK 22; and JEP 453, Structured Concurrency (Preview) , delivered in JDK 21. This feature simplifies concurrent programming by introducing structured concurrency to “treat groups of related tasks running in different threads as a single unit of work, thereby streamlining error handling and cancellation, improving reliability, and enhancing observability.”
After its review has concluded, JEP 471, Deprecate the Memory-Access Methods in sun.misc.Unsafe for Removal , has been promoted from Proposed to Target to Targeted for JDK 23. This JEP proposes to deprecate the memory access methods in the Unsafe class for removal in a future release. These unsupported methods have been superseded by standard APIs, namely; JEP 193, Variable Handles , delivered in JDK 9; and JEP 454, Foreign Function & Memory API , delivered in JDK 22.
Build 23-loom+4-102 of the Project Loom early-access builds are based on JDK 23 Build 25 and improves the implementation of Java monitors (synchronized methods) to work better with virtual threads.
Build 22-jextract+5-33 of the Project Jextract early-access builds , also known as Project Panama, are based on JDK 22 and provides a recommendation in which the quarantine attribute from the bits may need to be removed before using the jextract binaries on macOS Catalina or later.
Build 25 of the JDK 23 early-access builds was made available this past week featuring updates from Build 24 that include fixes for various issues . Further details on this release may be found in the release notes .
In his weekly Hashtag Jakarta EE blog , Ivar Grimstad , Jakarta EE Developer Advocate at the Eclipse Foundation, has provided an additional update on the upcoming GA release of Jakarta EE 11.
Nine (9) specifications, namely - Jakarta Annotations 3.0 , Jakarta Authorization 3.0 , Jakarta Contexts and Dependency Injection 4.1 , Jakarta Expression Language 6.0 , Jakarta Interceptors 2.2 , Jakarta RESTful Web Services 4.0 , Jakarta Persistence 3.2 , Jakarta Validation 3.1 and Jakarta WebSocket 2.2 - have been finalized for Jakarta EE 11.
Five (5) specifications, namely - Jakarta Concurrency 3.1 , Jakarta Data 1.0 , Jakarta Faces 4.1 , Jakarta Pages 4.0 and Jakarta Servlet 6.1 - should have their respective reviews completed during the week of June 3, 2024.
And reviews for the remaining two (2) specifications, Jakarta Authentication 3.0 and Jakarta Security 4.0 , should start during the week of June 10, 2024.
Discussing the remaining work required for the GA release, Grimstad stated:
There is some work to be done on the TCK and the specification documents before the release reviews of the Jakarta EE 11 Platform , Jakarta EE 11 Web Profile , and Jakarta EE 11 Core Profile specifications can start. This will likely happen in late June or early July, so we are on track according to the release plan .
GlassFish 7.0.15, fifteenth maintenance release in the 7.0.0 release train, provides improvements in documentation, dependency upgrades and notable resolutions to issues such as: a ClassCastException due to improper classloader matching in the Weld BeanDeploymentArchive interface; cluster monitoring data not being displayed in the Admin Console; and an IllegalArgumentException in the toString() method, defined in the Application class, due to a bundle without descriptor being valid. More details on this release may be found in the release notes .
TornadoVM 1.0.5, the fifth maintenance release , ships with bug fixes and improvements such as: support for Vector types at the API level in the variants of the Floatx<Width> class with variants of Intx<Width> class; an improved OpenCL build log; an improvements in the TornadoOptions and TornadoLogger classes where all options (debug, events, etc.) have been moved to the former and all debugging has been moved to the latter.
Spring Framework
It was a very quiet week at Spring compared to the release activity during the week of May 20, 2024.
Following the release of Spring Boot 3.3.0, 3.2.6 and 3.1.12, versions 3.0.16 and 2.7.21 were released this past week featuring many dependency upgrades and notable bug fixes: when graceful shutdown of Tomcat is aborted, it may report that it completed successfully; and resolving an instance of the BuildpackReference class, created from a URL-like String, can fail on Windows. Further details on these releases may be found in the release notes for version 3.0.16 and version 2.7.21 .
Spring Cloud 2023.0.2, codenamed Leyton, and 2022.0.7 Enterprise Edition have been released featuring featuring bug fixes and notable updates to sub-projects: Spring Cloud Kubernetes 3.1.2; Spring Cloud Function 4.1.2; Spring Cloud OpenFeign 4.1.2; Spring Cloud Stream 4.1.2; and Spring Cloud Gateway 4.1.4. This release is based on Spring Boot 3.3.0. More details on this release may be found in the release notes .
The first milestone release of Spring AI 1.0.0 delivers new features such as: a new ChatClient fluent API, composed of the ChatClient interface and Builder inner class, providing methods to construct an instance of a Prompt class, which is then passed as input to an AI model; eight (8) new AI models; updated existing models; and support for Testcontainers. Developers interested in learning more can follow this example application .
Versions 3.3.0-RC1, 3.2.5 and 3.1.12 of Spring Shell have been released featuring a breaking change that replaces the use of the Spring Boot ApplicationArguments interface with a plain String array in the ShellRunner interface and its implementations. Default methods to bridge new methods were created and old methods were deprecated with a plan to remove them in Spring Shell 3.4.x. This is part of on-going work to remove all Spring Boot classes from the Spring Shell core package. These versions build upon Spring Boot 3.3.0, 3.2.5 and 3.1.12, respectively, and JLine 3.26.1. Further details on these releases may be found in the release notes for version 3.3.0-RC1 , version 3.2.5 and version 3.1.12 .
The release of Helidon 4.0.9 ships with notable changes such as: a resolution to an IndexOutOfBoundsException generated from the first(String) method, defined in the Parameters interface, due to index 0 being out of bounds for an array of length 0; a refactor of the OCI metrics library code is organized so other implementations can extend common types without having to also include the OCI metrics library CDI module; and improvements to the WebClientSecurity class against absent or disabled tracing. More details on this release may be found in the release notes .
The release of Quarkus 3.11 delivers notable changes such as: a new OidcRedirectFilter interface to dynamically customize OIDC redirects; initial support of security integration for the WebSockets Next extension; and a new Infinispan Cache extension that will replace the now-deprecated @CacheResult annotation. Further details on this release may be found in the release notes . InfoQ will follow up with a more detailed news story.
The Micronaut Foundation has released version 4.4.3 of the Micronaut Framework featuring Micronaut Core 4.4.10 , bug fixes, improvements in documentation and updates to modules: Micronaut Data and Micronaut Test Resources . More details on this release may be found in the release notes .
WildFly 32.0.1, first maintenance release , delivers component upgrades and notable resolutions to issues such as: a ClassCastException when running live-only High Availability policy in the messaging-activemq subsystem; a possible NoSuchElementException upon deploying multiple OpenAPI endpoints; and restoration of the io.smallrye.opentelemetry module to the OpenTelemetryDependencyProcessor class as this module is required on the deployment classpath since that contains the CDI provider method providing the implementation of the OpenTelemetry Tracer interface. Further details on this release may be found in the release notes .
The release of Hibernate Reactive 2.3.1.Final ships with dependency upgrades and a resolution to a NullPointerException due to a method that converts the generated ID from the database to a ResultSet was not implemented. This release is compatible with Hibernate ORM 6.5.2.Final. More details on this release may be found in the release notes .
Apache Software Foundation
Apache Maven 4.0.0-beta-3 provides bug fixes, dependency upgrades and improvements such as: initial support for Maven 4.0 API to be usable outside of the runtime; changes in the PathType interface to control the type of path where each dependency can be placed; and support for the fatjar , a dependency type to be used when dependency is considered self contained. Further details on this release may be found in the release notes .
Similarly, Apache Maven 3.9.7 ships with bug fixes, dependency upgrades and new features: support for wildcards in an OS version to specify wildcard in the OS version tag; and the ability to ignore transitive dependency repositories using the mvn -itr command. More details on this release may be found in the release notes .
Maintaining alignment with Quarkus, the release of Camel Quarkus 3.11.0, composed of Camel 4.6.0 and Quarkus 3.11.0, provides resolutions to notable issues such as: Quarkus Infinispan not compatible with Camel Infinispan due to differences in Infinispan version support; and improved auto-configuration by moving the options for the SupervisingRouteController interface into its own group. Further details on this release may be found in the release notes .
Version 7.2.0 of JobRunr , a library for background processing in Java that is distributed and backed by persistent storage, has been released featuring bug fixes, dependency upgrades and new features such as: support for Spring Boot 3.3.0 where JobRunr now declares the spring-boot-starter dependency with a provided scope; support for Kotlin 2.0.0 (support for Kotlin 1.7.0 ahs been dropped); and deleting a job using the JobScheduler or JobRequestScheduler classes will be retried if a ConcurrentJobModificationException is thrown. More details on this release may be found in the release notes .
The release of JHipster 8.5.0 delivers: support for Spring Boot 3.3.0; a resolution to issues with OIDC claims in the SecurityUtils class when the syncUserWithIdp boolean is set to false ; and resolutions to multiple issues with SonarCloud , used by JHipster for code quality. Further details on this release may be found in the release notes . InfoQ will follow up with a more detailed news story.
Versions 14.0.53+75 and 14.0.51+73 of JDKUpdater , a new utility that provides developers the ability to keep track of updates related to builds of OpenJDK and GraalVM. Introduced in mid-March by Gerrit Grunwald , principal engineer at Azul, these releases include: an update in the base URL for CVE details; and modifications related to menu items. More details on this release may be found in the release notes for version 14.0.53+75 and version 14.0.51+73 .
The release of Gradle 8.8 delivers: full support for JDK 22; a preview feature to configure the Gradle daemon JVM using toolchains; improved IDE performance with large projects; and improvements to build authoring, error and warning messages, the build cache , and the configuration cache . Further details on this release may be found in the release notes .
About the Author
Rate this article, this content is in the java topic, related topics:.
- Development
- Architecture & Design
- AI, ML & Data Engineering
- Spring Cloud
- JBoss WildFly
- Project Loom
- Apache Camel
- Spring Boot
- Hibernate Reactive
- Project Panama
Related Editorial
Related sponsored content, popular across infoq, what's new in c# 13: enhanced params, performance boosts, and new extension types, asp.net core updates in .net 9 preview 4: support for openapi doc generation, hybridcache and more, java news roundup: java turns 29, kotlin 2.0, semantic kernel for java 1.0, more openjdk updates, retrieval-augmented generation (rag) patterns and best practices, spring ecosystem releases focus on spring boot, spring session and spring security, architecture modernization with nick tune, related content, the infoq newsletter.
A round-up of last week’s content on InfoQ sent out every Tuesday. Join a community of over 250,000 senior developers. View an example
![](http://academicwritinghelp.pw/777/templates/cheerup1/res/banner1.gif)
COMMENTS
In this brief article, we've examined a few ways to access and read a resource from the classpath using Spring. This includes eager and lazy loading, and on the filesystem or in a jar. As always, all of these examples are available over on GitHub. .: Get started with Spring Boot and with core ...
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.
@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 ...
The resource paths in application context constructor values may be a simple path (as shown above) which has a one-to-one mapping to a target Resource, or alternately may contain the special "classpath*:" prefix and/or internal Ant-style regular expressions (matched using Spring's PathMatcher utility). Both of the latter are effectively wildcards
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 ...
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.
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 ...
If you have to get the resource from a hardcoded path then use this way: import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.Resource; //... Resource stateFile = new ClassPathResource("state.json"); edited Mar 18 at 14:06. Saikat. 15.8k 20 114 139.
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 ...
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()); //...
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.
Spring Resource. Resource abstracts from the actual type of an underlying resource, such as a file or class path resource. It can be used to identify local or remote resources. Spring ApplicationContext contains the getResource method, which returns a resource handle for the specified resource type. It can be a classpath, file, or URL resource.
Classpath Scanning and Managed Components. Most examples in this chapter use XML to specify the configuration metadata that produces each BeanDefinition within the Spring container. The previous section ( Annotation-based Container Configuration) demonstrates how to provide a lot of the configuration metadata through source-level annotations.
Spring - Injecting Resource using @Value annotation. This example shows how Resource instance can be injected directly with @Value annotation. public class MyBean { @Value("classpath:myResource.txt") private Resource myResource; ...
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.
Create a new ClassPathResource for Class usage.. The path can be relative to the given class, or absolute within the class path via a leading slash. If the supplied Class is null, the default class loader will be used for loading the resource.. This is also useful for resource access within the module system, loading a resource from the containing module of a given Class.
Spring 3.1 also introduces the new @PropertySource annotation as a convenient mechanism for adding property sources to the environment. We can use this annotation in conjunction with the @Configuration annotation: @Configuration @PropertySource("classpath:foo.properties") public class PropertiesWithJavaConfig { //...
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 -
This is part of on-going work to remove all Spring Boot classes from the Spring Shell core package. These versions build upon Spring Boot 3.3.0, 3.2.5 and 3.1.12, respectively, and JLine 3.26.1.
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.
As of Spring Framework 6.1, you can configure a custom PropertySourceFactory via the factory attribute in @TestPropertySource in order to support a different file format such as JSON, YAML, etc. Each path is interpreted as a Spring Resource. A plain path (for example, "test.properties") is treated as a classpath resource that is relative to the ...