How to Read Application.properties File in Spring Boot

In this Spring Boot commodity nosotros will expect at the application.properties file . We will look at the different options to use the backdrop in Spring Kick.

Introduction

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

It also provides a powerful mechanism to inject the custom backdrop in our application using the application.properties file. For a complete list of the OOTB properties, please refer to the documentation. This postal service covers how to define custom properties and how to utilize these custom backdrop in our application.

1. application.properties File.

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

  1. Packet it with the jar.
  2. Load from the file organization on startup.

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

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

2. Setting up Application

Allow'due south get-go our journey past creating a simple web application. We can use the IDE or Leap Initializr to bootstrap our application.

Spring boot web module image

Click on the "Generate" button to download the projection construction in your local machine. The next step is to import the projection in the Java editor. Our Spring Kick configuration file will be bachelor under the src/chief/resources directory.

application_properties file

Past default, this file will be empty (nosotros volition add values in the afterward department).Leap also support the property configuration using the .yml file. If yous adopt the .yml, create application.yml file in the same file location. Nosotros are using the .properties type in this tutorial.

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

Permit's add a custom property to in the application.properties file:

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

3. Property Injection Using @Value Note

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

  1. In the constructors
  2. On the Bean fields.

Allow'south create a Residue controller and provide a configurable welcome message to all client:

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

When we run our application, our welcome controller volition return the holding injected from the awarding.backdrop file through @Value annotation.

Spring Boot Configuration Properties - Welcome Message

3.i. Using Constructor Argument.

Nosotros accept the pick to use the @Value annotation to pass as the constructor argument. Let'south take an example, where we desire to pass a default value to the constructor:

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

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

Bound Boot is flexible enough to provide an selection to handle the IllegalArgumentException in case the property is missing. We tin pass an choice value in case the property is missing in the awarding.backdrop file. We can pass the default value by adding colon (:) after the key followed by the default value.

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

4. Using @ConfigurationProperties

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

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

If I take to use these property files in the Spring application.

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

@Value("${proprties}") notation is handy and piece of cake to use, but it will actually be a very tedious process if we take several properties. Bound Kicking has introduced the @ConfigurationProperties annotation to handling these properties in a more clean manner with an option to validate these configurations value.

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

Allow's encounter how to set email configurations without injectingindividuall properties:

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

Once we run to a higher place application, all properties defined in the property files with prefix "mail" volition automatically exist bind /assigned to this object. Read @ConfigurationProperties in Spring Kicking for more detail.

5. Overriding Default Backdrop

To override the backdrop defined in the default awarding.backdrop file, we just need to define the property in our projection configuration file with custom value. Bound Boot load these property files in sure society and information technology will brand sure that the configuration divers in project application.backdrop file take precedence. Let'southward take an example, where we similar to change the default port of the tomcat, add the following property in the project configuration file:

                server.port = 8090              

six. Multiple Lines in Property File

If our property has a long value, we can add backslash graphic symbol to pause it in multi-line and ameliorate the overall readability of the property. Let'southward run into how to do this in the application.backdrop file:

                javadevjournal.welcome.message= A warm and long greeting from Javadevjournal Squad!! to show \                                 how we tin can use the backslash character to improve the overall \                                 readability of the file.              

7. Custom Backdrop Type Conversion

All properties defined in the awarding.properties file is of type String (it'due south a text file). Spring framework comes a long listing of type convertors to convert string to other types based on the type declared in the application. Permit's expect at the following example:

                javadevjournal.max.login.retry=3 javadevjournal.enable.guest.checkout=truthful              

Spring detects variable type automatically and volition perform type conversion before injection;

                public void DefaultWelcomeService(@Value("${javadevjournal.init.secret.cardinal}") 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 secret cardinal {}", secretKey); }              

8. Arrays, List, Set in application.backdrop

There are sure apply cases where we want to define a collection of values for our application. Define the holding values separated past comma in the application.properties file.

                javadevjournal.init.keys= 1,2,3,4,5,6              

Define the belongings in the grade as List, Gear up or Array and Jump will practise the auto conversion for us.

                @Value("${javadevjournal.init.keys}") private int[] keys;  @Value("${javadevjournal.init.keys}") private List < Integer > keyList;  /**  * Our Welcome display bulletin which volition use the welcome bulletin property injected through the  * @Value notation.welcome  * @return welcome message  */ @GetMapping("/welcome") public String displayWelcomeMsg() {     LOG.info("keys as integer assortment {}", keys);     LOG.info("keys every bit integer listing {}", keyList);     return welcomeMsg; }              

Here is the output from the console:

                2020-02-17 11:ten:39.560  INFO 87750 --- [nio-8080-exec-1] c.j.controller.WelcomeController         : keys as integer array [1, two, three, 4, 5, vi] 2020-02-17 eleven:10:39.563  INFO 87750 --- [nio-8080-exec-1] c.j.controller.WelcomeController         : keys every bit integer list [1, 2, 3, 4, 5, half-dozen]              

eight.1. Custom separator in the property file.

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

                javadevjournal.init.keys= 1;ii;3;iv;v;6              
                @Value("#{'${javadevjournal.init.keys.new.delimiter}'.split(';')}")  private List < Integer > newKeys;              

That's the ability of Jump EL, which did this play tricks for usa.Leap Boot injected the property as a regular string. The split() method in our expression separate the input and finally it's converted in to the Integer list.

[pullquote align="normal"]At that place are no naming convention rules, only it's highly recommended to accept a consistent naming convention for your custom properties. [/pullquote]

9. Jump Profile (Environment Specific Files)

Spring Profiles provides a powerful and easy fashion to command lawmaking and configuration based on the surround. UsingJump Profilesits possible to segregate parts of our application and get in just available in certain environments. One of the most interesting and powerful features provided by Spring Kick is the ability to define profile specific awarding.properties file and agile these past chief awarding.properties file.

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

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

You can ascertain properties as per your requirements.Use the bound.profiles.active holding to aid Spring Kick choose the correct configurations for u.s.a..

                leap.profiles.active=staging              

Nosotros are setting the active profile as staging. With above setting,, Spring Kicking will load the properties divers in the awarding-staging.backdrop besides the main application.properties file.For more detail, read Spring Profiles

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

10. External application.properties File.

How about a situation where we don't desire to put the backdrop within the jar? Take an example of the username and password for all the endpoints. Nosotros don't want this sensitive data in the jar file yet we similar to use the same level of flexibility to alter the configurations without irresolute the code base.

Spring Boot provides an option to read custom belongings file directly from the filesystem of the runtime environs. We tin store this custom application.properties file on the server and notify Spring Kick to load this file on the startup.Use the spring.config.additional-location property to configure

                java -jar javadevjournal.jar -Dspring.config.additional-location="external_file_location"              

Summary

In this commodity, we discussed the awarding.backdrop file in Spring Boot. Nosotros saw the different options to define the custom properties for our awarding 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. As always, the source lawmaking for this application is bachelor on the GitHub.

woodhationge1967.blogspot.com

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

0 Response to "How to Read Application.properties File in Spring Boot"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel