In this tutorial, I'm going to explain how we can use multiple message properties files in a spring boot application. We can use this approach when we need to differentiate message properties into multiple files.
Just think you have a requirement of keeping messages error messages, API responses in different message property files. We can use the following approach to keep errors and API responses in different files.
Technologies Going to Use,
- Java 1.8
- Spring Boot: 2.3.4.RELEASE
- Lombok
- Gradle
- Intellij Idea for IDE
Create a Spring Boot Application
Here I'm using spring initializr to generate a spring boot project with all the dependencies I need for this tutorial.
If you are really new to Spring Boot, Please follow our article on How to Create a Spring Boot Project.
Here I've selected the following dependencies to create spring boot project using spring initilizr,
- Spring Web - contains common web-specific utilities for both Servlet and Portlet environments.
- Lombok - The coolest plugin to spicing up your java. Never write another getter or equals method again, with one annotation your class has a fully-featured builder, Automate your logging variables, and much more.
If you need to learn how we can use Lombok in spring boot follow our article Guide to use Lombok In Spring Boot.
Adding Message Properties Into The Spring Boot Project
Here I'm creating 2 message property files in resources, to keep errors and API responses. In order to do that, just create two files in src/main/resources/messages folder with naming as below,
- api_error_messages.properties
- api_response_messages.properties
Then add following message key and value pairs into those files,
- api_error_messages.properties,
- api_response_messages.properties,
Setup MessageSources Bean With Introducing Multiple Message Properties
Now we have our error message and API response property files inside the project. Let's introduce those files to the Spring Boot application using message source bean.
Here I'm using separate @Configuration class to set up this MessageSource bean, You can use the same approach or use already available configuration class to define this MessageSource Bean.
Now we can access these message properties inside our application anywhere we need. Here I'll demonstrate it with @PostConstruct method in Main Class,
Start the application and output should look like below.
Conclusion
Thanks for reading our latest article on How To Handle Multiple Message Properties In Spring Boot with practical usage.
If you are looking for spring boot based practical application development tutorials, just check our article series.
You can get source code for this tutorial from our GitHub repository.
Top comments (0)