Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the knowledge points of Spring Boot configuration file

2025-02-25 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly explains "what are the knowledge points of the Spring Boot configuration file", interested friends may wish to take a look. The method introduced in this paper is simple, fast and practical. Next let the editor to take you to learn "what are the knowledge points of the Spring Boot configuration file"!

Configuration basis

The default configuration file location for Spring Boot is: src/main/resources/application.properties. The configuration of Spring Boot applications can be concentrated in this file. According to the different Starter modules we introduce, you can define various configuration information here, such as container port name, database link information, log level and so on. For example, we need to customize the service port number of the web module. We can add server.port=8888 to application.properties to specify the service port 8888, or we can specify the application name through spring.application.name=hello (this name will be registered as the service name in the Spring Cloud application).

In addition to using traditional properties files, Spring Boot configuration files also support YAML files, which are now widely recommended.

YAML is a highly readable format used to express a sequence of data. YAML (English pronunciation: / "j æ m camel") is a highly readable format. YAML refers to a variety of other languages, including C, Python, Perl, and takes inspiration from XML, the data format of email (RFC 2822). Clark Evans first published the language in 2001, and Ingy d ö t Net and Oren Ben-Kiki are also co-designers of the language. There are already several programming or scripting languages that support (or parse) this language. YAML is a recursive abbreviation for "YAML Ain't a Markup Language" (YAML is not a markup language). When the language was developed, YAML actually meant "Yet Another Markup Language" (still a markup language), but renamed it with reverse acronyms to emphasize that the language is data-centric rather than markup language. The syntax of AML is similar to that of other high-level languages and can simply express data forms such as lists, hash tables, scalars, and so on. It uses blank symbol indentation and a lot of appearance-dependent features, and is particularly suitable for expressing or editing data structures, various profiles, dumping debug content, and document outlines (for example, many email title formats are very close to YAML). Although it is more suitable for expressing hierarchical (hierarchical model) data structures, there is also an exquisite syntax for expressing relational model (relevance) data. Because YAML uses white space and branches to separate data, it is particularly suitable for grep/Python/Perl/Ruby operations. Its most easy-to-use feature is to skillfully avoid a variety of closed symbols, such as quotation marks, various parentheses, etc., which become complex and illegible in the nest structure. Wikipedia

The configuration format adopted by YAML is not expressed in the form of simple key-value pairs like the configuration of properties, but in the form of indentation similar to outline. For example: the following piece of YAML configuration information

Environments:

Dev:

Url: http://dev.bar.com

Name: Developer Setup

Prod:

Url: http://foo.bar.com

Name: My Cool App

The equivalent properties configuration is as follows.

Environments.dev.url= http://dev.bar.com

Environments.dev.name=Developer Setup

Environments.prod.url= http://foo.bar.com

Environments.prod.name=My Cool App

Through the configuration mode of YAML, we can see that the configuration information is indented step by step, its structure is clearer and easier to read, and the number of characters in the configuration content is significantly reduced. In addition, YAML can define multiple different environment configurations in a single file by using the spring.profiles attribute. For example, when specified as a test environment, server.port will use port 8882, while in a prod environment, server.port will use port 8883, and if no environment is specified, server.port will use port 8881.

Server:

Port: 8881

-

Spring:

Profiles: test

Server:

Port: 8882

-

Spring:

Profiles: prod

Server:

Port: 8883

Note: YAML currently has some shortcomings, it cannot load the configuration through the @ PropertySource annotation. However, YAML loads properties in memory in an orderly manner, so when the information in the configuration file needs to have a sequential meaning, the YAML configuration method has an advantage over the properties configuration file.

Custom parameter

In addition to setting the predefined configuration properties in each Starter module in the configuration file of Spring Boot, we can also define some custom properties that we need in the configuration file. For example, add: to application.properties:

Book.name=SpringCloudInAction

Book.author=ZhaiYongchao

Then, in the application, we can load these custom parameters through the @ Value annotation, such as:

@ Component

Public class Book {

@ Value ("${book.name}")

Private String name

@ Value ("${book.author}")

Private String author

/ / omit getter and setter

}

The @ Value annotation supports two expressions for configuration when loading attribute values:

One is the PlaceHolder method we described above, with the format ${...} and PlaceHolder in curly braces.

You can also use SpEL expressions (Spring Expression Language) in the format # {...} with SpEL expressions in curly braces

Parameter reference

Between the parameters in application.properties, we can also refer to them directly by using PlaceHolder, like the following settings:

Book.name=SpringCloud

Book.author=ZhaiYongchao

Book.desc=$ {book.author} is writing "${book.name}"

The book.desc parameter refers to the book.name and book.author properties defined above, and the final value of this property is ZhaiYongchao is writing "SpringCloud".

Use random numbers

In some special cases, there are some parameters that we want to load each time it is not a fixed value, such as: key, service port, etc. In Spring Boot's property configuration file, we can generate random int values, longs, or string strings by using the ${random} configuration, so that we can easily configure the random generation of properties instead of coding the logic in the program.

There are several main ways to configure ${random}, which can be used by readers as a reference.

# Random string

Com.didispace.blog.value=$ {random.value}

# Random int

Com.didispace.blog.number=$ {random.int}

# Random long

Com.didispace.blog.bignumber=$ {random.long}

Random numbers within # 10

Com.didispace.blog.test1=$ {random.int (10)}

# 10-20 random number

Com.didispace.blog.test2=$ {random.int [10,20]}

This configuration method can be used to set up scenarios such as application ports to avoid the trouble of port conflicts during local debugging.

Command line argument

Recall that in the Quick start in this chapter, we also introduced how to start the Spring Boot application, which mentioned how to start it using the command java-jar command. In addition to starting the application, this command can also specify the parameters of the application on the command line, such as: java-jar xxx.jar-- server.port=8888, set the server.port property directly on the command line, and set the port to start the application to 8888.

When the Spring Boot application is started on the command line, there are two consecutive minus signs-- that is, the identification of the assignment of the attribute value in the application.properties. So, the java-jar xxx.jar-- server.port=8888 command is equivalent to adding the attribute server.port=8888 to the application.properties.

Modifying attribute values through the command line is a very important feature of Spring Boot. Through this feature, we have theoretically made the attributes we apply are variable before startup, so both the port number and database connection can be changed when the application starts, unlike previous Spring applications that build different environments in the compiler through Maven's Profile. The biggest difference is that Spring Boot's approach allows the packaged content of the application to run through development, testing, and online deployment, while the content of packages built in each environment of different Profile solutions in Maven is essentially different. However, if each parameter needs to be specified from the command line, this is obviously not a good solution, so let's take a look at how to implement a multi-environment configuration in Spring Boot.

Multi-environment configuration

When we develop any application, usually the same set of programs will be applied and installed in several different environments, such as development, testing, production, etc. The database address, server port and other configurations of each environment will be different, if you have to frequently modify the configuration file when packaging for different environments, it will be very tedious and error-prone.

For multi-environment configuration, the basic idea of various project building tools or frameworks is the same. By configuring multiple configuration files for different environments, and then using the packaging command to specify what needs to be packaged, Spring Boot is no exception, or simpler.

In Spring Boot, the multi-environment configuration file name needs to meet the format of application- {profile} .properties, where {profile} corresponds to your environment ID, such as:

Application-dev.properties: development environment

Application-test.properties: test environment

Application-prod.properties: production environment

As to which specific configuration file will be loaded, it needs to be set through the spring.profiles.active property in the application.properties file, and its value corresponds to the {profile} value in the configuration file. For example, spring.profiles.active=test will load the contents of the application-test.properties configuration file.

Next, take the configuration of different service ports in different environments as an example to conduct a sample experiment.

Create different configuration files application-dev.properties, application-test.properties, application-prod.properties for each environment

Different server.port properties are set in all three files, for example, the dev environment is set to 1111 Magi test environment, 2222 Magi prod environment is set to 3333

Set spring.profiles.active=dev in application.properties, that is to say, the default setting is dev environment.

Test the loading of different configurations

Execute java-jar xxx.jar and observe that the service port is set to 1111, that is, the default development environment (dev)

Execute java-jar xxx.jar-- spring.profiles.active=test and observe that the service port is set to 2222, that is, the configuration of the test environment (test)

Execute java-jar xxx.jar-- spring.profiles.active=prod and observe that the service port is set to 3333, that is, the configuration of the production environment (prod)

According to the above experiment, the configuration ideas of multi-environment can be summarized as follows:

Configure common content in application.properties, and set spring.profiles.active=dev to the development environment as the default configuration

Configure different content for each environment in application- {profile} .properties

Use the command line to activate the configuration of different environments

Loading sequence

In the above example, we put all the configuration content needed by the Spring Boot application into the project project, although we have been able to support multiple environments through spring.profiles.active or Maven. However, as our team grows and the division of labor becomes more and more detailed, often we do not need to let developers know the details of the test or build environment, but want each environment's own person in charge (QA or operations) to centrally maintain this information. Then if the configuration content is still stored in this way, the modification of the configuration of different environments will have to obtain the project content to modify the configuration content, which becomes very inconvenient when there are a lot of applications. At the same time, the configuration content is visible to developers, which is also a security hazard in itself. In this regard, there are many frameworks and tools to externalize the configuration content, and Spring Cloud Config is one of them. In order to better understand the loading mechanism of Spring Cloud Config, we need to have a certain understanding of the loading mechanism of Spring Boot to data files.

In order to override the values of each attribute more reasonably, Spring Boot uses the following special attribute loading order:

The parameters passed in on the command line.

Properties in SPRING_APPLICATION_JSON. SPRING_APPLICATION_JSON is what is configured in the system environment variable in JSON format.

The JNDI property in java:comp/env.

The system properties of Java, which can be obtained through System.getProperties ().

Operating system environment variables

Random properties configured through random.*

Located outside the current application jar package, for different {profile} environments, such as application- {profile} .properties or YAML defined configuration files

Located within the current application jar package, for different {profile} environments, such as application- {profile} .properties or YAML defined configuration files

Application.properties and YAML configuration content located outside the current application jar package

Application.properties and YAML configuration content within the current application jar package

In the class modified by the @ Configuration annotation, the properties defined by the @ PropertySource annotation

Apply default properties, using content defined by SpringApplication.setDefaultProperties

The priority is from high to low in the above order, and the smaller the number, the higher the priority.

As you can see, items 7 and 9 read the configuration file outside the application jar package, so the principle of externalizing the configuration is to start from here and specify the loading location of the external configuration file to replace the configuration content in the jar package. Through this implementation, our project becomes very clean in the configuration. We only need to place the configuration needed for development locally, while the configuration of other environments can be ignored and maintained by the person in charge of the corresponding environment.

2.x New Featur

Relaxed Binding 2.0 is introduced in Spring Boot 2.0, which makes a lot of improvements to the original property binding function to help us load and read configuration information more easily in Spring applications. Let's talk about the configuration improvements in Spring Boot 2.0.

Profile binding

Simple type

When loading configuration properties in Spring Boot 2.0, in addition to removing special characters as in version 1.x, configurations are matched and loaded in all lowercase. Therefore, the following four configurations are equivalent:

Properties format:

Spring.jpa.databaseplatform=mysql

Spring.jpa.database-platform=mysql

Spring.jpa.databasePlatform=mysql

Spring.JPA.database_platform=mysql

Yaml format:

Spring:

Jpa:

Databaseplatform: mysql

Database-platform: mysql

DatabasePlatform: mysql

Database_platform: mysql

Tips: it is recommended to use all lowercase matching-delimiter, such as spring.jpa.database-platform=mysql

List Typ

Use [] in the properties file to locate the list type, such as:

Spring.my-example.url [0] = http://example.com

Spring.my-example.url [1] = http://spring.io

Comma-separated configurations are also supported, and the above is equivalent to the following configuration:

Spring.my-example.url= http://example.com,http://spring.io

In the yaml file, you can use the following configuration:

Spring:

My-example:

Url:

-http://example.com

-http://spring.io

Comma separation is also supported:

Spring:

My-example:

Url: http://example.com, http://spring.io

Note: the configuration of List type in Spring Boot 2.0 must be contiguous, otherwise a UnboundConfigurationPropertiesException exception will be thrown, so the following configuration is not allowed:

Foo [0] = a

Foo [2] = b

The above configuration is possible in Spring Boot 1.x, and since foo [1] is not configured, its value will be null

Map Typ

The standard configuration of the Map type in properties and yaml is as follows:

Properties format:

Spring.my-example.foo=bar

Spring.my-example.hello=world

Yaml format:

Spring:

My-example:

Foo: bar

Hello: world

Note: if the key of type Map contains characters other than alphanumeric and -, you need to enclose them in [], for example:

Spring:

My-example:

'[foo.baz]': bar

Environment property binding

Simple type

Through lowercase conversion to. Replace _ to map the contents of the configuration file, such as the configuration of the environment variable SPRING_JPA_DATABASEPLATFORM=mysql will have the same effect as setting spring.jpa.databaseplatform=mysql in the configuration file.

List Typ

Because the [and] symbols cannot be used in environment variables, use _ instead. Any number surrounded by an underscore is considered an array of []. For example:

MY_FOO_1_ = my.foo [1]

MY_FOO_1_BAR = my.foo [1] .bar

MY_FOO_1_2_ = my.foo [1] [2]

In addition, if the final environment variable ends with a number and an underscore, the final underscore can be omitted, for example, the first and third items in the above example are equivalent to the following configuration:

MY_FOO_1 = my.foo [1]

MY_FOO_1_2 = my.foo [1] [2]

System property binding

Simple type

System attributes are similar to those in file configuration, which are bound by removing special characters and converting lowercase. For example, the following command line parameters will achieve the effect of configuring spring.jpa.databaseplatform=mysql:

-Dspring.jpa.database-platform=mysql

-Dspring.jpa.databasePlatform=mysql

-Dspring.JPA.database_platform=mysql

List Typ

The binding of system properties is similar to that of file properties, marked by [], such as:

-D "spring.my-example.url [0] = http://example.com"

-D "spring.my-example.url [1] = http://spring.io"

Similarly, he also supports comma separation, such as:

-Dspring.my-example.url= http://example.com,http://spring.io

Reading of attributes

After introducing the content of property binding in Spring Boot 2.0 above, you can see that we can have many different expressions for an attribute, but if we want to read the attribute in the environment of the Spring application, the unique name of each attribute conforms to the following rules:

Pass. Separate the elements

The last one。 Separate the prefix from the attribute name

Must be letters (amurz) and numbers (0-9)

Must be lowercase letters

Separate words with a hyphen-

The only other characters allowed are [and], which are used for the index of List

Cannot start with a number

So, if we want to read the configuration of spring.jpa.database-platform in the configuration file, we can write:

This.environment.containsProperty ("spring.jpa.database-platform")

The content of spring.jpa.database-platform configuration cannot be obtained in the following ways:

This.environment.containsProperty ("spring.jpa.databasePlatform")

Note: this feature is also required when using @ Value to get configuration content.

New binding API

A new binding API has been added to Spring Boot 2.0 to help us get configuration information more easily. Here is an example to help you understand more easily:

Example 1: simple type

Suppose there is such a configuration in the propertes configuration: com.didispace.foo=bar

We create a corresponding configuration class for it:

@ Data

@ ConfigurationProperties (prefix = "com.didispace")

Public class FooProperties {

Private String foo

}

Next, you can get the configuration information like this through the latest Binder:

@ SpringBootApplication

Public class Application {

Public static void main (String [] args) {

ApplicationContext context = SpringApplication.run (Application.class, args)

Binder binder = Binder.get (context.getEnvironment ())

/ / bind simple configuration

FooProperties foo = binder.bind ("com.didispace", Bindable.of (FooProperties.class). Get ()

System.out.println (foo.getFoo ())

}

}

Example 2: List type

What if the configuration content is of type List? For example:

Com.didispace.post [0] = Why Spring Boot

Com.didispace.post [1] = Why Spring Cloud

Com.didispace.posts [0] .title = Why Spring Boot

Com.didispace.posts [0] .content = It is perfect!

Com.didispace.posts [1] .title = Why Spring Cloud

Com.didispace.posts [1] .content = It is perfect too!

It's still easy to get these configurations, which can be done like this:

ApplicationContext context = SpringApplication.run (Application.class, args)

Binder binder = Binder.get (context.getEnvironment ())

/ / bind List configuration

List post = binder.bind ("com.didispace.post", Bindable.listOf (String.class). Get ()

System.out.println (post)

List posts = binder.bind ("com.didispace.posts", Bindable.listOf (PostInfo.class). Get ()

System.out.println (posts)

At this point, I believe you have a deeper understanding of "what are the knowledge points of the Spring Boot configuration file?" you might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report