In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-31 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
This article mainly shows you "how to achieve SpringBoot load configuration file", the content is easy to understand, clear, hope to help you solve your doubts, the following let the editor lead you to study and learn "how to achieve SpringBoot load configuration file" this article.
I. brief introduction
In the actual project development process, we often need to extract some variables from the code and put them in the configuration file in order to manage the service configuration information more uniformly and flexibly. For example, the connection parameter configuration of database, eureka, zookeeper, redis, mq, kafka and other service components, as well as our custom project parameter configuration variables.
Of course, in fact, according to the current business requirements, we often customize the parameters and then inject them into the code for flexible use!
Today, let's talk about several ways to load configuration files in SpringBoot!
When the SpringBoot project is enabled, the two configuration files bootstrap.properties or bootstrap.yml will be loaded by default (the two priority files are highest); then application.properties or application.yml; will be loaded if the variable spring.profiles is configured, and the corresponding application- {profile} .properties or application- {profile} .yml files will also be loaded, with profile as the corresponding environment variable, such as dev. If there is no configuration, the configuration file of profile=default will be loaded.
Although it is no problem to say that the configuration items are all written in the same configuration file, we still want to write them separately in many cases, so it will be clearer, for example, the configuration of zookeeper is written in zookeeper.properties, the configuration related to the database is written in datasource.properties, etc., so we need to set up to load the external configuration file!
How to achieve it? let's take a look at it!
2. code practice 2.1. parameter loading is realized through @ value annotation.
When we want to inject a variable into a class, we can simply inject parameters through the @ value annotation!
For example, in the application.properties file, configure a variable key of config.name with a value of zhangsan
/ / Parameter definition config.name=zhangsan
Then in the corresponding class, you can inject it with the parameter @ value!
@ RestControllerpublic class HelloController {@ Value ("${config.name}") private String config; @ GetMapping ("config") public String config () {return JSON.toJSONString (config);}}
When injecting configuration with @ value annotations, there is usually a requirement that the variables in the annotations must be defined in advance in the application.properties file, otherwise an error message will be started!
Of course, if we don't want it to hold it wrong, we can give it a default value of xxx, such as:
@ Value ("${config.name:xxx}") private String config
In this way, the SpringBoot project will not report an error when it is enabled!
2.2.The parameter loading is realized by @ ConfigurationProperties annotation
In some scenarios, the @ value annotation does not meet all of our needs. For example, the data type of the parameter configuration is an object or an array. Using @ ConfigurationProperties at this time would be a better choice!
Configure parameters of an object type
For example, in the application.properties file, when we want to configure an object type parameter, we can do this!
/ / Parameter definition config2.name=demo_1config2.value=demo_value_1
Then, create a configuration class Config2 that maps the defined variables to the configuration class.
@ Component@ConfigurationProperties (prefix = "config2") public class Config2 {public String name; public String value; / /... get, set}
The way to read data is also very simple, just inject it directly into the corresponding class.
RestControllerpublic class HelloController {@ Autowired private Config2 config2; @ GetMapping ("config2") public String config2 () {return JSON.toJSONString (config2);}}
Configure a parameter of type Map
For example, in the application.properties file, when we want to configure a parameter of type Map, we can do this!
/ / Parameter definition config3.map1.name=demo_id_1_nameconfig3.map1.value=demo_id_1_valueconfig3.map2.name=demo_id_2_nameconfig3.map2.value=demo_id_2_value
Then, create a configuration class Config3 that maps the defined variables to the configuration class.
@ Component@ConfigurationProperties (prefix = "config3") public class Config3 {private Map map1 = new HashMap (); private Map map2 = new HashMap (); / /... get, set}
The way data is read is similar!
RestControllerpublic class HelloController {@ Autowired private Config3 config3; @ GetMapping ("config3") public String config3 () {return JSON.toJSONString (config3);}}
Configure a parameter of type List
For example, in the application.properties file, when we want to configure a parameter of type List, we can do this!
/ / Parameter definition config4.userList [0] .enable = maillist_1_enableconfig4.userList [0] .name = maillist_1_nameconfig4.userList [0] .value = maillist_1_valueconfig4.userList [1] .enable = maillist_2_enableconfig4.userList [1] .name = maillist_2_nameconfig4.userList [1] .value = maillist_2_valueconfig4.userList [2] .enable = maillist_3_enableconfig4.userList [2] .name = maillist_3_nameconfig4.userList [2] .value = maillist_3_value
Then, create a configuration class Config4 that maps the defined variables to the configuration class.
@ Component@ConfigurationProperties (prefix = "config4") public class Config4 {private List userList; public List getUserList () {return userList;} public void setUserList (List userList) {this.userList = userList;}} public class UserEntity {private String enable; private String name; private String value; / /. Get, set}
The way data is read is similar!
@ RestControllerpublic class HelloController {@ Autowired private Config4 config4; @ GetMapping ("config4") public String config4 () {return JSON.toJSONString (config4);}} 2.3.Loading configuration files through @ PropertySource annotation
As we explained at the beginning, most of the time, we want to write the configuration file separately, for example, the service profile corresponding to the zookeeper component is the service profile corresponding to the zookeeper.properties,redis component, the service profile corresponding to the zookeeper.properties,redis component is redis.properties and so on.
How should we load this custom configuration file into the Spring container?
In fact, the method is also very simple, through @ PropertySource can be achieved!
First, under the resources resource folder, create two configuration files, test.properties and bussiness.properties, as follows!
Contents of test.properties file:
Aaa.a1=aa1123aaa.a2=aa2123aaa.a3=aa3123aaa.a4=aa4123
Contents of bussiness.properties file:
Bbbb.a1=bb1123bbbb.a2=bb2123bbbb.a3=bb3123bbbb.a4=bb4123
Just load the configuration file on the SpringBoot startup class!
SpringBootApplication@PropertySource (value = {"test.properties", "bussiness.properties"}) public class PropertyApplication {public static void main (String [] args) {SpringApplication.run (PropertyApplication.class, args);}}
The way data is read is similar!
@ RestControllerpublic class HelloController {@ Value ("${aaa.a2}") private String a2; @ Value ("${bbbb.a1}") private String bbbbA1; @ GetMapping ("a2") public String a2 () {return JSON.toJSONString (a2);} @ GetMapping ("bbbbA1") public String bbbbA1 () {return JSON.toJSONString (bbbbA1);}}
If we only need to use the value of the custom configuration file in the business, there is no problem with this introduction, but if some custom variables need to be used at the start of the project, there will be some problems with this approach, for the following reasons:
The translation means:
While using @ PropertySource on @ SpringBootApplication seems like a convenient and easy way to load custom resources in the environment, it is not recommended because SpringBoot prepares the environment before refreshing the application context. Any keys defined with @ PropertySource are loaded too late to have any impact on automatic configuration.
Therefore, if some parameters are startup variables, it is recommended that you define them in an application.properties or application.yml file so that there will be no problem!
Or, use the Custom Environment processing Class to load the configuration file!
2.4. Load the configuration file by defining the environment processing class
The implementation is also simple: first, create a class that implements the EnvironmentPostProcessor interface, and then load the configuration file yourself.
Public class MyEnvironmentPostProcessor implements EnvironmentPostProcessor {@ Override public void postProcessEnvironment (ConfigurableEnvironment environment, SpringApplication application) {/ / Custom profile String [] profiles = {"test.properties", "bussiness.properties", "blog.yml"} / / add for (String profile: profiles) {/ / find the file Resource resource = new ClassPathResource (profile) under the classpath path; / / load it as a PropertySource object and add it to the Environment environment environment.getPropertySources () .addLast (loadProfiles (resource)) }} / / load a single configuration file private PropertySource loadProfiles (Resource resource) {if (! resource.exists ()) {throw new IllegalArgumentException ("Resource" + resource + "does not exist");} if (resource.getFilename (). Contains (".yml")) {return loadYaml (resource);} else {return loadProperty (resource) }} / * load configuration file in properties format * @ param resource * @ return * / private PropertySource loadProperty (Resource resource) {try {/ / load a Properties object Properties properties = new Properties (); properties.load (resource.getInputStream ()); return new PropertiesPropertySource (resource.getFilename (), properties) from the input stream } catch (Exception ex) {throw new IllegalStateException ("failed to load configuration file" + resource, ex);}} / * load the configuration file in yml format * @ param resource * @ return * / private PropertySource loadYaml (Resource resource) {try {YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean (); factory.setResources (resource) / / load a Properties object from the input stream Properties properties = factory.getObject (); return new PropertiesPropertySource (resource.getFilename (), properties);} catch (Exception ex) {throw new IllegalStateException ("failed to load configuration file" + resource, ex);}
Next, under the resources resource directory, we also need to create a file, META-INF/spring.factories, and load the custom environment processing class into the Spring processor through spi, which will be called automatically when the project starts!
# enable our custom environment processing class org.springframework.boot.env.EnvironmentPostProcessor=com.example.property.env.MyEnvironmentPostProcessor
This custom environment to deal with classes, will be relatively more flexible, first write a general configuration file parsing class, support the reading of properties and yml files, and then inject it into the Spring container, basically once and for all!
Finally, let's introduce yml file reading
In the above, most of us take properties as an example. Some people may have stepped on the trap and used the @ PropertySource annotation to load the yml file in the project, resulting in a direct error report because @ PropertySource does not support direct parsing of yml files, but can only parse properties files.
What if I want to parse the yml file separately, and I don't want to get a custom environment handling class to read the file?
The mode of operation is also very simple, take the custom blog.yml file as an example!
Contents of blog.yml file:
Pzblog: name: helloWorld
Then, create a configuration class that reads the yml file
@ Configurationpublic class ConfigYaml {/ * load a custom configuration file in YML format * @ return * / @ Bean public static PropertySourcesPlaceholderConfigurer properties () {PropertySourcesPlaceholderConfigurer configurer = new PropertySourcesPlaceholderConfigurer (); YamlPropertiesFactoryBean yaml = new YamlPropertiesFactoryBean (); yaml.setResources (new ClassPathResource ("blog.yml")); configurer.setProperties (yaml.getObject ()); return configurer;}}
The way data is read is similar!
@ RestControllerpublic class HelloController {@ Value ("${pzblog.name}") private String pzblogName; @ GetMapping ("pzblogName") public String pzblogName () {return JSON.toJSONString (pzblogName);}} these are all the contents of the article "how to implement SpringBoot loading configuration files". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!
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.