In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
What is the parameter and configuration of SpringBoot externalized configuration source code? in view of this problem, this article introduces the corresponding analysis and solution in detail, hoping to help more partners who want to solve this problem to find a more simple and feasible method.
Comprehensive actual combat
We have explained the principle and source code analysis of Spring Boot externalization configuration, and we will briefly demonstrate how to use different types of parameters and configurations in Spring Boot through a specific example. We will use the functions of passing parameters on the command line, default configuration file application.properties, obtaining parameters based on profile configuration parameters, @ Value annotation, and associating Bean based on type-safe @ ConfigurationProperties annotation.
As the external configuration of Spring Boot has been simplified, it is very convenient for us to use it in practice. Here I have created a standard Spring Boot project with a version of 2.2.1.RELEASE. First, let's take a look at the directory structure of the project.
The core dependency introduced in pom.xml is spring-boot-starter-web, and the corresponding dependency source code is as follows.
Org. Springframework. Boot spring- boot- starter-web
The SpringbootConfigApplication class is the startup class for the Spring Boot project, and we won't cover it too much.
The ConfigController class is the Controller that receives the request. A default getConfigParams method is defined inside the ConfigController class, in which the parameter values obtained in different ways are printed. The relevant source code is as follows.
@ RestController public class ConfigController {@ Value ("${user. Username}") private String username; @ Value ("${user. Password}") private String password; @ Resource private LoginUserConfig loginUserConfig; @ Value ("${projectName: unknown}") private String projectName; @ RequestMapping ("/") public String getConfigParams () {/ / start the command to pass the parameter System. Out. Println ("Command config projectName:" + projectName); / / Parameter System configured through the appl ication configuration file. Out. Println ("Application config Username System. Out. Println (" Application config Password: "+ password); / / parameters configured through @ ConfigurationProperties annotation System. Out. Println (" ConfigurationProperties config Username: "+ login UserConfig. GetUsername ()); System. Out. Println (" ConfigurationProperties config Password: "+ login UserConfig. GetPassword ()); return";}
This class is specified as a Controller that can receive requests through the @ RestController annotation and is instantiated. In this class, do not use @ Value annotation, @ Resource annotation to get the parameters set by different ways. The access request is provided through the getConfigParams method. After the request is received, the values of the parameters in different ways are printed.
First, let's look at the source of the value obtained through @ Value. In this example, there are two ways to set the corresponding value:
Application.properties configuration files and command line parameters.
With regard to command-line parameters, as we have mentioned before, the basic delivery method is to pass in the form of "- name=value'" when executing the command to start the project. Combined with an example, the delivery method is as follows.
Java-jar springboot-config-0. 0.1-SNAPSHOT. Jar-projectName=SpringBoot
In the ConfigController class, we can see that the basic format for @ Value is @ Value ("${param}"), but we use @ Value ("${param:default}") for command-line arguments. Both of these methods are commonly used in practice, while the second method passes the default value through a colon separator, using the specified default value when the param parameter does not exist or is not configured in the application.
Take the current instance as an example, if the projectName parameter is not specified in the startup command, and the default value "unknown" is not specified when @ Value gets it, an exception will be thrown when the startup command is executed. This is a situation we need to pay attention to when using @ Value.
It is easier to set the parameters in the application.properties configuration file, just set the corresponding key=value value in the corresponding file, for example, the configuration source code in application.properties in this example is as follows.
# Public configuration, any environment starts with 8080-side server. Port=8080 spring. Profiles. Active=dev
However, in the process of practice, we often encounter situations where different environments require different configuration files. If it is more troublesome to modify the configuration files or repackage each environment, we can use the Profile configuration function provided by Spring Boot to solve the problem. The three properties configuration files provided in our example are intended to demonstrate the basic use of the Profile configuration.
In general, one or more properties configuration files are created in a project according to the size of the environment, and their corresponding naming formats and related functions are as follows.
* applcation.properties: public configuration.
* application-dev.properties: development environment configuration.
.application-test.properties: test the environment configuration.
Application-prod.properties: production environment configuration.
Of course, the named "dev'" test and "prod" can be customized, and when these configurations will be used, you can activate spring.profiles in the application.properties configuration file. Active parameter to control.
For example, do a public configuration in applcation.properties, and then activate the configuration of the specified environment with the following configuration.
Spring. Profiles.active = prod
Where "prod" compares to application-prod.properties in the file name. Spring Boot gets the configuration file applcation.properties during processing, and then splices through the specified profile value "prod" to get the name and path of the application-prod.properties file. The specific steps and principles of loading and splicing have been discussed in the previous chapter, which can be reviewed with examples.
In the above example, we activate the configuration environment for dev, and the configuration in application-dev.properties is as follows.
# Test environment user name and account user. Username=test-admin user. Password=test-pwd
At this point, by accessing the corresponding request, the corresponding printed log in the getConfigParams method is as follows.
Application config Username: test- admin Application config Password: test- pwd
If you want to activate the configuration of the production environment, just configure spring.profiles. Exe in application.properties. Active=prod is fine.
We have expanded so much on the acquisition of @ Value parameter values and Profile-based parameter configuration. The use of @ Value also includes injecting ordinary strings, operating system attributes, expression results, file resources, URL resources, and so on. You can refer to the official documentation and related examples for further study.
In the use of @ Value above, we can inject configuration to a single property, but it is not convenient and flexible if there are many configuration properties or if the configuration properties themselves have a hierarchical structure. Therefore, Spring Boo provides a type-safe configuration.
In ConfigController, we inject a LoginUserConfig class through @ Resource, which associates the properties property with the LoginUserConfig property through the @ ConfigurationProperties annotation, thus implementing type-safe configuration. The source code for LoginUserConfig is as follows.
@ Component@Configurat ionProperties (prefix = "user") public class LoginUserConfig {private String username; private String password; / / omit the getter/setter method}
In the source code of the LoginUserConfig class, the @ ConfigurationProperties annotation specifies that the configuration property prefixed with user is bound to the corresponding property of the LoginUserConfig class when instantiated, and the class is instantiated with @ Component.
Since the specified configuration document is dev, the values of user.username and user.password in the above dev configuration document will be bound to the username and password properties of the LoginUserConfig class, respectively. After injection in ConfigController, the corresponding attribute value can be obtained. Similarly, when the request is executed, the corresponding printed log in the getConfigParams method is as follows.
ConfigurationProperties config Username: test-admin
ConfigurationProperties config Password: test- pwd
The above example demonstrates only one case of the @ ConfigurationProperties binding attribute. When Spring Boot binds the Environment attribute to the Bean of the @ ConfigurationProperties annotation, it can also use some loose rules, that is, the Environment attribute name and the Bean attribute name do not need to match exactly.
For example, if there is a firstName attribute in the object User, then the following configuration items will match in the configuration file.
User. FirstName / / Standard Hump naming Syntax
User. First-name / / short horizontal lines are separated and are recommended for. Properties and. In the yml file
User. The first_ name / / underscore is used for. Optional formats for properties and yml files
USER_ FIRST _ NAME / / in uppercase, recommended for system environment variables
At the same time, type-safe attribute configuration can also be combined with @ Validated annotation for constraint verification of attributes, such as determining whether it is not empty, whether it is the correct mobile phone number (mailbox) format, whether it is the correct date, and so on.
You can try to expand with this example.
Finally, we review the key points of the examples in this section as a whole, first we set up multiple environment configuration files based on the Profile mechanism, and then through spring. Profiles. Active configuration specifies which environment parameter values are used; then binds these configuration attributes to class attributes or Bean objects through @ Value and @ ConfigurationProperties annotations; and finally obtains and uses them in a specific scenario (in this example, printing).
In practice, we will also encounter the problem of priority, such as some parameters are specified directly through the command line parameters, then it will overwrite the parameters in the configuration file with the same name. For example, if the application configuration file is placed in the project sibling directory, it takes precedence over the configuration in the jar package, and so on. We have covered all these contents in the principle section, and readers can refer to this example to verify and learn one by one.
This paper mainly introduces the parameter transfer process and configuration file loading in Spring Boot, especially the loading mechanism based on profile. Loading, default configuration, configuration priority and other operations are all located in the ConfigFileApplicationListener class, which is worth taking the time to study.
Finally, because this chapter involves a lot of source code, the logic level is deep, and different configuration modes will form different combinations and form more scenes, it is recommended to track each step of the operation through debug in the learning process, so that we can better understand the whole process.
This is the answer to the question about the parameters and configuration of the external configuration source code of SpringBoot. I hope the above content can be of some help to you. If you still have a lot of doubts to be solved, you can follow the industry information channel to learn more about it.
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.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.