In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
This article will explain in detail how SpringBoot reads external configuration files. The editor thinks it is very practical, so I share it for you as a reference. I hope you can get something after reading this article.
1.SpringBoot profile
SpringBoot uses a profile named after application as the default global profile. Supports configuration files ending with the properties suffix or YAML ending with the yml/yaml suffix.
Take setting the application port as an example
Sample properties file (application.properties):
Server.port=80
Sample YAML file (application.yml):
Server: port: 80
When both properties and yml/yaml configuration files exist at the same directory, properties configuration priority > YAML (YML) configuration priority
two。 Configuration file directory
SpringBoot configuration files can be placed under multiple paths, and the configuration priority varies from path to path.
Directories can be placed (priority from high to low)
. / config/ (under the current project path config directory);. / (under the current project path); classpath:/config/ (under the classpath config directory); classpath:/ (under the classpath config).
The priority is from high to bottom, and the configuration with high priority will override the configuration with low priority.
SpringBoot loads the configuration files from all four locations and complements the configuration
We can see from things like ConfigFileApplicationListener, where the DEFAULT_SEARCH_LOCATIONS property sets the loaded directory:
Private static final String DEFAULT_SEARCH_LOCATIONS = "classpath:/,classpath:/config/,file:./,file:./config/"
Then the comma is parsed into Set in the getSearchLocations method, where the inner class Loader is responsible for the loading process of the configuration file.
Includes loading the configuration of the environment specified by profile, loading in application+'-'+name format.
Multiple directory configurations exist at the same time
Next, let's take port configuration as an example.
Set the port to 8888 in the resources/ directory, 9999 in the resources/config directory, 6666 in the project path, and 7777 in the project path config directory.
]
Final running result:
Tomcat started on port (s): 7777 (http) with context path'/ beedo'
Started BeedoApplication in 4.544 seconds (JVM running for 5.335)
It can be demonstrated by the method of control variables.
The priority is from high to bottom, and the configuration with high priority will override the configuration with low priority.
3. Custom configuration properties
SpringBoot provides a lot of configuration, but usually we need to customize our own configuration to apply to our own system, such as you need to configure a default username password as the login of the system.
First, create an entity class for configuration injection, and use the @ ConfigurationProperties annotation for batch injection, or you can use the Spring underlying annotation @ Value ("${user.username}") to achieve the agreed effect.
@ Component@ConfigurationProperties (prefix = "user") public class Login {private String username; private String password;...}
Or @ Value
@ Componentpublic class Login {private String username; private String password;...}
Configuration file writing
# yml file writing method user: username: admin password: 12 percent properties writing method login.username=adminlogin.password=123
Write a junit test case to see if the configured values are injected properly:
@ RunWith (SpringRunner.class) @ SpringBootTestpublic class DeployApplicationTests {@ Autowired private Login login; @ Testpublic void contextLoads () {System.out.println (login);}}
Judging from the output, the value has been injected normally.
Login {username='admin', password='123'}
Comparison of @ ConfigurationProperties and @ Value annotations
Compare whether the item @ ConfigurationProperties@Value full injection supports loose binding (Relaxed Binding) whether SpEL does not support JSR303
Loose binding: the binding between hump naming (userName), horizontal stitching (user-name) and underscore (user_name) can be recognized as loose binding.
JSR303: check mailbox, null, digital format and other data through @ Email,@Nullable,@Digits and other annotations. For more information, please refer to the Chinese document of IBM: https://www.ibm.com/developerworks/cn/java/j-lo-jsr303/index.html.
@ ConfigurationProperties is usually used to inject full configuration into a class
@ Value is usually used to inject some specific configuration values
The @ ConfigurationProperties method can be used for automatic mapping between configuration files and entity fields, but the fields must provide a set method, while fields decorated with @ Value annotations do not need to provide a set method
Custom configuration Tip
When writing the configuration, you will find that there is no prompt for the custom configuration, which makes it very troublesome for you to use the custom configuration. In fact, SpringBoot has already prepared the prompt for us. You only need to introduce relevant dependencies to prompt.
When you do not join a dependency, idea will prompt you as follows:
When you add a dependency, the idea prompt disappears, and there are corresponding prompts when writing a custom configuration:
Org.springframework.boot spring-boot-configuration-processor true
It needs to run.
4. Specify profile
Usually we configure the configuration in the main configuration file at the beginning of application, so as the project grows and the number of configuration items increases, the file will become very bloated. In fact, SpringBoot has already considered this problem. SpringBoot provides @ PropertySource and @ ImportResource annotations for loading external configuration files.
@ PropertySource is usually used for property loading configuration files. Note that the @ PropertySource annotation does not support loading yaml files, but supports properties files.
@ ImportResource is commonly used to load Spring's xml configuration file
@ PropertySource use
Assembling properties Profil
Creating a yaml file under sources/config named user.properties content is the same as the configuration of the user above
The Login class can be written as follows
@ PropertySource (value = {"classpath:config/user.properties"}) @ Component@ConfigurationProperties (prefix = "user") public class Login {private String username; private String password;...}
After running it, it can also achieve the effect of loading configuration.
Load multiple configuration questions at the same time
If you are careful, you will find that the attribute value in the @ PropertySource annotation is an array. If multiple configuration files are loaded at the same time and different values are set for the same property in different configuration files, which one will Spring recognize?
With doubt, we can test through the method of control variables, and the specific process will be described in more detail.
@ PropertySource (value = {"classpath:config/user1.properties", "classpath:config/user2.properties"})
Conclusion: the loading order of Spring is from left to right, and the attribute values loaded first will be overridden after loading.
Assembling yaml Profil
If you have obsessive-compulsive disorder, you must want to load the yaml configuration file, then you can load the yaml file through the PropertySourcesPlaceholderConfigurer class, and change the original user.properties to the user.yaml,Bean configuration class with the following code, the Login configuration class is the same as at the beginning.
@ Beanpublic static PropertySourcesPlaceholderConfigurer loadProperties () {PropertySourcesPlaceholderConfigurer configurer = new PropertySourcesPlaceholderConfigurer (); YamlPropertiesFactoryBean yaml = new YamlPropertiesFactoryBean (); / / yaml.setResources (new FileSystemResource ("classpath:config/user.yml")); / / File path introduces yaml.setResources (new ClassPathResource ("config/user.yml")); / / class path introduces configurer.setProperties (yaml.getObject ()); return configurer;}
If you run it, you can still achieve the effect of loading configuration.
@ ImportResource use
SpringBoot proposes a zero XML configuration, so SpringBoot does not recognize the xml configuration file of Spring in the project by default. In order to be able to load xml's configuration file, SpringBoot provides the @ ImportResource annotation which can load Spring's xml configuration file, usually added to the startup class.
@ ImportResource (value = {"classpath:/beans.xml"}) @ SpringBootApplication (scanBasePackages = {"team.seagull.client"}) public class DeployApplication {public static void main (String [] args) {SpringApplication.run (DeployApplication.class, args);}} other questions
There is a problem of garbled codes in Chinese when idea uses .properties files.
The default code for .properties in idea is GBK, and usually our project is encoded in UTF-8, so the program will have garbled problems when reading.
Solution: open the following options in idea: File- > Sttings- > Editor- > FileEncodings
Change GBK to UTF-8 and check
Transparent native-to ascill conversion (converted to ascii code at run time)
This is the end of the article on "how SpringBoot reads external configuration files". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, please share it for more people to see.
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.