banner



4310.5 - Property Disposition Handbook 1 to 4 Family Properties

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

Introduction

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

It as well provides a powerful mechanism to inject the custom properties in our application using the awarding.properties file. For a complete list of the OOTB properties, please refer to the documentation. This mail service covers how to define custom properties and how to use these custom properties in our awarding.

ane. application.properties File.

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

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

Retrieve of the property file equally 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 command our application (defining the username and password for API integration).

2. Setting up Application

Let'south kickoff our journey by creating a simple spider web awarding. We can employ the IDE or Jump Initializr to bootstrap our application.

Spring boot web module image

Click on the "Generate" button to download the project structure in your local machine. The next pace is to import the project in the Java editor. Our Spring Kicking configuration file will be bachelor under the src/main/resources directory.

application_properties file

By default, this file will be empty (nosotros will add values in the later department).Spring too back up the property configuration using the .yml file. If yous prefer the .yml, create application.yml file in the same file location. Nosotros are using the .properties blazon in this tutorial.

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

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

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

3. Property Injection Using @Value Note

The nearly common manner to inject these properties are through the @Value annotation. We have the option to use this annotation in

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

Let'due south create a Remainder controller and provide a configurable welcome message to all customer:

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

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

Spring Boot Configuration Properties - Welcome Message

three.1. Using Constructor Argument.

Nosotros take the option to use the @Value annotation to pass every bit the constructor argument. Allow's take an example, where we desire to pass a default value to the constructor:

                public void DefaultWelcomeService(@Value("${javadevjournal.init.secret.key}") Cord 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 desire to inject, it'll throw IllegalArgumentException [/pullquote]

Spring Boot is flexible enough to provide an option to handle the IllegalArgumentException in example the holding is missing. Nosotros can pass an pick value in example the property is missing in the awarding.backdrop file. We can pass the default value by calculation colon (:) afterward the key followed by the default value.

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

four. Using @ConfigurationProperties

This note is helpful if our backdrop have some common context.Consider following entries in the belongings file.

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

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

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

@Value("${proprties}") note is handy and easy to utilize, but it will really be a very ho-hum process if we have several backdrop. Bound Boot has introduced the @ConfigurationProperties annotation to treatment these properties in a more clean way with an option to validate these configurations value.

                #Database Configuration db.driver =org.hsqldb.jdbcDriver db.username =examination db.password =test db.tablePrefix =_prefix #SMTP Configuration post.from [electronic mail protected] mail.host [email protected] mail.port =25 postal service.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              

Let'southward meet how to prepare up email configurations without injectingindividuall properties:

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

In one case we run above awarding, all properties defined in the property files with prefix "postal service" will automatically be bind /assigned to this object. Read @ConfigurationProperties in Jump Boot for more than detail.

5. Overriding Default Backdrop

To override the properties defined in the default awarding.properties file, we but demand to define the property in our project configuration file with custom value. Spring Boot load these holding files in certain social club and it will make sure that the configuration defined in project application.backdrop file accept precedence. Permit'due south take an example, where we like to change the default port of the tomcat, add together the following belongings in the project configuration file:

                server.port = 8090              

6. Multiple Lines in Property File

If our belongings has a long value, we can add backslash character to suspension it in multi-line and meliorate the overall readability of the property. Let's come across how to exercise this in the application.properties file:

                javadevjournal.welcome.bulletin= A warm and long greeting from Javadevjournal Team!! to show \                                 how nosotros can employ the backslash character to improve the overall \                                 readability of the file.              

vii. Custom Properties Blazon Conversion

All properties defined in the application.properties file is of blazon String (it'due south a text file). Jump framework comes a long list of type convertors to convert string to other types based on the type alleged in the application. Let'southward look at the following example:

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

Leap detects variable type automatically and will perform type conversion before 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 note is working for our secret key {}", secretKey); }              

8. Arrays, List, Prepare in application.backdrop

In that location are certain use cases where we want to define a collection of values for our application. Ascertain the belongings values separated past comma in the application.backdrop file.

                javadevjournal.init.keys= one,2,3,4,v,vi              

Ascertain the belongings in the class equally List, Set or Array and Spring volition do 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 use the welcome message holding injected through the  * @Value annotation.welcome  * @render welcome message  */ @GetMapping("/welcome") public String displayWelcomeMsg() {     LOG.info("keys as integer array {}", keys);     LOG.info("keys every bit integer list {}", keyList);     return welcomeMsg; }              

Hither is the output from the console:

                2020-02-17 xi:10:39.560  INFO 87750 --- [nio-8080-exec-1] c.j.controller.WelcomeController         : keys as integer array [one, ii, iii, 4, v, 6] 2020-02-17 xi:x:39.563  INFO 87750 --- [nio-8080-exec-1] c.j.controller.WelcomeController         : keys equally integer list [one, 2, iii, 4, 5, half-dozen]              

8.one. Custom separator in the belongings file.

Jump Kick uses a comma every bit the default delimiter when nosotros define the list in the application.backdrop file. Framework provide the choice to handle the properties in instance we want to apply a unlike delimiter for the list.

                javadevjournal.init.keys= 1;2;three;4;v;6              
                @Value("#{'${javadevjournal.init.keys.new.delimiter}'.split(';')}")  individual List < Integer > newKeys;              

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

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

9. Jump Profile (Environment Specific Files)

Spring Profiles provides a powerful and easy way to control lawmaking and configuration based on the environment. UsingBound Profilesits possible to segregate parts of our application and make it only available in certain environments. 1 of the nigh interesting and powerful features provided by Jump Kick is the power to define profile specific awarding.properties file and agile these by chief application.backdrop file.

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

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

You can define backdrop as per your requirements.Employ the bound.profiles.active property to help Leap Boot choose the right configurations for u.s..

                spring.profiles.active=staging              

We are setting the agile profile equally staging. With in a higher place setting,, Spring Kicking will load the properties defined in the application-staging.backdrop as well the primary awarding.backdrop file.For more detail, read Jump Profiles

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

10. External application.properties File.

How almost a situation where we don't want to put the properties inside the jar? Accept an case of the username and password for all the endpoints. Nosotros don't want this sensitive data in the jar file yet we like to use the same level of flexibility to change the configurations without changing the lawmaking base.

Spring Boot provides an option to read custom belongings file directly from the filesystem of the runtime surroundings. We can store this custom awarding.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, nosotros discussed the application.properties file in Spring Kicking. Nosotros saw the different options to ascertain the custom properties for our application using this configuration file. At the finish of this section, we talked almost how to load the sensitive information using an external file in our application. Equally e'er, the source code for this application is available on the GitHub.

mcinnesfacter.blogspot.com

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

0 Response to "4310.5 - Property Disposition Handbook 1 to 4 Family Properties"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel