In engineering, there is usually a need to read different profiles depending on the environment, and for spring boot, the default read is Application.yml or application.properties. The mechanism of profile is also provided in order to distinguish different environments. For example, when a configuration file for a development environment is application-dev.yml, by setting spring.profiles.actives = Dev, when the program starts, it will take precedence over The value in the Application-dev.yml, and then go to the value in the APPLICATION.YML.
Use placeholders to reduce information redundancy
To minimize information redundancy, you can combine the placeholder in spring properties to reduce configuration file authoring and maintenance, for example. In Application.properties, I configure the URL of the database as follows;
Spring: DataSource: url:jdbc:mysql://${dbs.database.host}:${dbs.database.port}/${ Dbs.database.databasename}
So, in the case of configuration files for different environments, I just need to configure:
DBS: Database: host:x.x.x.x port:3306 username:user password:password databasename: Test
To determine the reading order of a configuration file by modifying the value of--spring.config.location
As mentioned earlier, spring boot determines the priority of values in different environment profiles based on the variables of the profile, but the reading order of the configuration files is read APPLICATION.YML First and then read applicaiotn-{profile}.yml. So if you follow the previous section of the setup, the program will error, prompting to find ${dbs.database.host} this variable. In this way, spring properties will define this placeholder variable before parsing the placeholder.
To solve this problem, you can modify the properties reading order by setting--spring.config.location in the program startup parameters, for example, you can set the
--spring.config.location=classpath:/config/application-test.yml,classpath:/config/application.yml
In this way, the contents of the APPLICATION-TEST.YML will be read first, avoiding the error.
Spring boot one way to read different configuration files in different environments