Spring Boot Properties
How to use external files type properties to display messages or set up your Spring Boot 2 Application. (Spring Boot Properties).
There are several ways to consume properties files in JAVA. But today you’ll learn how to do it with Spring Boot 2.
By default a Spring Boot 2 application created with the official pivotal Initializr creates an application.properties file in the src/main/resources folder. If is not your case and you are “converting” a MAVEN project into a Spring Boot application, you must create that file manually.
Spring Boot does its magic behind and automatically you can access any value of your application.properties by putting the following notation to a string variable.
Syntax: @Value (Spring Boot Expression) String variable; Example: @Value (${com.cristianruizblog.aplicacion.titulo}) String titulo;
But you don’t have to stick to it and put all your properties into the spring boot File. You can also create your own files and add them to the context of Spring by using a configuration file, let me show you how.
- Create your properties file within the src/main/resources folder:
- Creates a configuration file with this structure:
-
Package com.Cristianruizblog.properties_profiles.configuration; //I usually create a package only for configuration files Import org.Springframework.Context.Annotation.Configuration; Import org.Springframework.Context.Annotation.PropertySource; @Configuration @PropertySource("classpath:miarchivo.properties")//The file created in step 1 public class Location { }
-
- With the notation @Configuracion, that file is loaded within the context of Spring, and with the notation @PropertySource Spring framework identify where to go to and which file will read.
[alert]:
The properties must be Unique. To this I mean that if you have the same properties in several files Spring boot will not show you error but only use the value of the first file it read.
[BONUS]:
Spring Boot provides the possibility to alter its magic configuration using its properties File. In the following link you can see those configurations that you may modify for different spring Components. For example look for Thymeleaf with CTRL + F and note that the first configuration for Thymeleaf is to allow the template engine to cache, you can add that line to the file application.properties of your project and disable that functionality (false). Also read the comments of each line for more Information. Https://docs.spring.io/spring-boot/common-application-properties.html
Want to see a more detail example using multiple files and a better explanation in this topic?
Then watch the following video:
Do not forget to leave your comments about this post and also check my github repository:
https://github.com/cruizg93/CristianRuizBlog-SpringBootProperties