How to Read Properties File in Spring Boot Example

In this Leap Boot commodity we will look at the application.properties file . We will wait at the dissimilar options to use the properties in Spring Kicking.

Introduction

Spring Kick provides a ability and flexible mechanism for awarding configuration using the awarding.properties file . This machinery provides the flexibility to configure and change the application behaviour without changing the lawmaking in our awarding. The default application.properties comes up with a large list of configurations to boot strap our awarding. Spring Boot provide the option to change or override the application behaviour by overriding these configuration backdrop.

Information technology besides provides a powerful mechanism to inject the custom properties in our application using the application.backdrop file. For a complete list of the OOTB backdrop, please refer to the documentation. This mail covers how to define custom properties and how to apply these custom properties in our application.

1. application.properties File.

The application.properties file is a simple holding file with a central-value information to configure or externalize our application properties. Bound Boot provides multiple options to package this file in the application.

  1. Bundle it with the jar.
  2. Load from the file system on startup.

Think of the property file as the central control unit for your application. This file is useful for:

  1. Customize or override the default Spring framework behaviour (eastward.g. changing the server port, or timeout or caching).
  2. Custom properties to control our application (defining the username and countersign for API integration).

two. Setting upward Application

Permit's start our journey by creating a simple web application. Nosotros can employ the IDE or Spring Initializr to bootstrap our awarding.

Spring boot web module image

Click on the "Generate" push button to download the projection structure in your local machine. The next step is to import the project in the Java editor. Our Bound Kick configuration file will be available nether the src/main/resources directory.

application_properties file

Past default, this file volition exist empty (nosotros will add values in the later section).Spring also back up the property configuration using the .yml file. If you lot adopt the .yml, create application.yml file in the aforementioned file location. We are using the .properties type in this tutorial.

[pullquote align="normal"]Don't mix property and yml convention. Choose 1 and stick to that. [/pullquote]

Let'due south add a custom property to in the application.properties file:

                javadevjournal.welcome.message= A warm greeting from Javadevjournal Team!!              

3. Holding Injection Using @Value Notation

The most common style to inject these properties are through the @Value notation. We have the option to utilize this annotation in

  1. In the constructors
  2. On the Edible bean fields.

Let'due south create a Balance controller and provide a configurable welcome message to all client:

                import org.springframework.beans.factory.annotation.Value; import org.springframework.web.demark.notation.GetMapping; import org.springframework.web.bind.annotation.RestController;  @RestController public course WelcomeController {      // We are injecting the configuration bulletin from the application.properties file using @Value annotation     @Value("${javadevjournal.welcome.bulletin}")     private String welcomeMsg;      /**      * Our Welcome brandish message which will use the welcome message property injected through the      * @Value annotation.welcome      * @return welcome message      */     @GetMapping("/welcome")     public String displayWelcomeMsg() {         render welcomeMsg;     } }              

When we run our application, our welcome controller will return the property injected from the application.backdrop file through @Value annotation.

Spring Boot Configuration Properties - Welcome Message

3.1. Using Constructor Argument.

We have the option to utilise the @Value annotation to pass as the constructor argument. Allow's have an example, where we desire to pass a default value to the constructor:

                public void DefaultWelcomeService(@Value("${javadevjournal.init.secret.cardinal}") Cord secretKey) {     this.secretKey = secretKey;     LOG.info("@Value annotation is working for our secret key {}", secretKey); }              

[pullquote align="normal"]If Spring doesn't find the key you want to inject, it'll throw IllegalArgumentException [/pullquote]

Leap Boot is flexible plenty to provide an choice to handle the IllegalArgumentException in example the property is missing. We can pass an option value in case the belongings is missing in the awarding.properties file. We can laissez passer the default value past adding colon (:) after the key followed past the default value.

@Value("${javadevjournal.welcome.bulletin: Welcome!!!}") private String welcomeMsg;

4. Using @ConfigurationProperties

This annotation is helpful if our properties have some common context.Consider following entries in the holding file.

                user.firstName = Demo user.lastName = User user.greeting = Hullo Stranger user.blogName = javadevjournal.com              

If I have to use these property files in the Leap application.

public class SimpleSpringPropertyTest {     @Value("${user.firstName}") private Cord firstName;     @Value("${user.lastName}") private String lastName;  }

@Value("${proprties}") note is handy and easy to apply, but it volition actually be a very tedious procedure if we have several properties. Spring Kicking has introduced the @ConfigurationProperties annotation to handling these backdrop in a more than clean mode with an option to validate these configurations value.

                #Database Configuration db.driver =org.hsqldb.jdbcDriver db.username =test db.password =examination db.tablePrefix =_prefix #SMTP Configuration mail service.from [email protected] postal service.host [e-mail protected] mail.port =25 postal service.security.userName =exam mail.security.password =test #Server Configurations server.tomcat.httpPort =80 server.tomcat.sslPort =443 server.tomcat.ajpPort =444 server.tomcat.jmxPort =445              

Permit's see how to fix email configurations without injectingindividuall backdrop:

                @Configuration @ConfigurationProperties(prefix = "postal service") public class ApplicationConfigurationProp {      private String from;     individual String host;     private int port;      //getter and setter      public static grade Security {         private Cord userName;         private Cord password;          //getter and setter     } }              

Once we run in a higher place awarding, all properties defined in the property files with prefix "postal service" will automatically be bind /assigned to this object. Read @ConfigurationProperties in Spring Kicking for more particular.

5. Overriding Default Properties

To override the properties divers in the default application.backdrop file, we only need to define the property in our project configuration file with custom value. Bound Kicking load these property files in certain order and information technology will make certain that the configuration defined in project awarding.properties file have precedence. Allow'due south take an instance, where we like to change the default port of the tomcat, add the following property in the project configuration file:

                server.port = 8090              

vi. Multiple Lines in Property File

If our property has a long value, we can add backslash character to break information technology in multi-line and improve the overall readability of the belongings. Let'southward see how to do this in the application.properties file:

                javadevjournal.welcome.message= A warm and long greeting from Javadevjournal Squad!! to show \                                 how nosotros tin employ the backslash graphic symbol to improve the overall \                                 readability of the file.              

7. Custom Backdrop Blazon Conversion

All backdrop defined in the awarding.properties file is of blazon String (information technology'due south a text file). Leap framework comes a long listing of blazon convertors to convert cord to other types based on the type declared in the application. Let'due south look at the following example:

                javadevjournal.max.login.retry=iii javadevjournal.enable.guest.checkout=true              

Spring detects variable type automatically and will perform type conversion earlier injection;

                public void DefaultWelcomeService(@Value("${javadevjournal.init.secret.key}") String secretKey, @Value("${javadevjournal.max.login.retry}") int retry, @Value("${javadevjournal.enable.guest.checkout}") boolean enableGuestCheckout) {     this.secretKey = secretKey;     LOG.info("@Value annotation is working for our surreptitious central {}", secretKey); }              

viii. Arrays, Listing, Set in application.properties

In that location are certain use cases where we want to ascertain a collection of values for our awarding. Ascertain the property values separated by comma in the application.properties file.

                javadevjournal.init.keys= i,ii,iii,4,5,6              

Ascertain the property in the class every bit Listing, Fix or Array and Leap will practise the machine conversion for us.

                @Value("${javadevjournal.init.keys}") private int[] keys;  @Value("${javadevjournal.init.keys}") individual List < Integer > keyList;  /**  * Our Welcome display message which will employ the welcome message holding injected through the  * @Value annotation.welcome  * @return welcome bulletin  */ @GetMapping("/welcome") public String displayWelcomeMsg() {     LOG.info("keys equally integer array {}", keys);     LOG.info("keys every bit integer list {}", keyList);     return welcomeMsg; }              

Here is the output from the panel:

                2020-02-17 11:10:39.560  INFO 87750 --- [nio-8080-exec-i] c.j.controller.WelcomeController         : keys as integer array [1, two, 3, four, 5, 6] 2020-02-17 xi:ten:39.563  INFO 87750 --- [nio-8080-exec-1] c.j.controller.WelcomeController         : keys as integer listing [1, 2, 3, 4, five, half dozen]              

viii.1. Custom separator in the property file.

Spring Boot uses a comma as the default delimiter when we ascertain the listing in the application.properties file. Framework provide the option to handle the properties in case we desire to apply a different delimiter for the list.

                javadevjournal.init.keys= 1;ii;3;four;five;half-dozen              
                @Value("#{'${javadevjournal.init.keys.new.delimiter}'.carve up(';')}")  individual Listing < Integer > newKeys;              

That's the power of Leap EL, which did this trick for us.Spring Boot injected the property as a regular cord. The split() method in our expression split the input and finally it's converted in to the Integer listing.

[pullquote marshal="normal"]There are no naming convention rules, just information technology's highly recommended to have a consistent naming convention for your custom backdrop. [/pullquote]

9. Spring Profile (Environment Specific Files)

Leap Profiles provides a powerful and easy mode to control code and configuration based on the environment. UsingSpring Profilesits possible to segregate parts of our awarding and make it simply available in certain environments. I of the about interesting and powerful features provided by Bound Kicking is the ability to ascertain profile specific application.properties file and agile these past main application.properties file.

To use profile specific configuration files, we demand to the naming convention ofapplication-{profile}.properties where contour defines the proper name of the intended contour. It will load profile files from the same location as application.properties file.

  • application-local.backdrop
  • application-dev.properties
  • application-staging.properties
  • application-prod.properties

You tin can ascertain properties as per your requirements.Use the spring.profiles.active property to help Spring Kicking choose the correct configurations for us.

                spring.profiles.agile=staging              

We are setting the active profile as staging. With in a higher place setting,, Jump Boot will load the properties defined in the application-staging.properties too the main application.properties file.For more detail, read Leap Profiles

[pullquote marshal="normal"]The application.properties will always loaded, irrespective of the spring.profiles.active value. [/pullquote]

10. External application.properties File.

How about a state of affairs where we don't want to put the properties inside the jar? Have an instance of the username and countersign for all the endpoints. We don't desire this sensitive information in the jar file yet we like to apply the same level of flexibility to alter the configurations without irresolute the lawmaking base of operations.

Leap Kick provides an option to read custom property file directly from the filesystem of the runtime environment. Nosotros can store this custom awarding.properties file on the server and notify Jump Kicking to load this file on the startup.Use the bound.config.boosted-location belongings to configure

                coffee -jar javadevjournal.jar -Dspring.config.boosted-location="external_file_location"              

Summary

In this article, nosotros discussed the awarding.properties file in Spring Kicking. We saw the unlike options to ascertain the custom properties for our application using this configuration file. At the end of this section, we talked about how to load the sensitive data using an external file in our application. Equally always, the source code for this application is bachelor on the GitHub.

adameshence80.blogspot.com

Source: https://www.javadevjournal.com/spring-boot/spring-boot-configuration-properties/

0 Response to "How to Read Properties File in Spring Boot Example"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel