preface

We all know that springBoot is configured to uninstall the application.properties configuration file (or application.yml). But what if you want to separate configuration files for different environments (such as development, test, and production)? SpringBoot supports specifying different configuration files.

SpringBoot configuration file format

Properties. {profile} corresponds to the identity of your environment (not necessarily a. Properties file, but also a. Yml file). The profile value is customized by the developer. Springboot will read the profile by adding the corresponding parameter at startup. For example, we can define the following format:

Properties: development environment application-test.properties: test environment application-prod.properties: production environmentCopy the code

If no configuration file is specified during startup or the specified configuration file has no corresponding item, the system reads the configuration file from the default configuration file. The default configuration file is: application.properties (or application.yml)

Start the specified environment

We can specify the environment with the spring.profiles. Active parameter.

Suppose you now have two configuration files:

application.properties

server.port=8080
Copy the code

application-happy.properties

server.port=9090
Copy the code

If we do not specify the environment and start directly, it will start on port 8080:

Java jar springboot - 0.0.1 - the SNAPSHOT. The jarCopy the code

Method to start the specified environment

Command line start specified

Can be specified by adding -dspring.profiles. active=

For example, specify the happy environment:

java -jar "-Dspring.profiles.active=happy"Springboot 0.0.1 - the SNAPSHOT. The jarCopy the code

The default configuration file specifies

Add in application.properties

spring.profiles.active=happy
Copy the code

Start procedure:

Specified in IDEA

In the Run/Debug Configuration, you can configure the environment as follows:

Remove the environment designation from application.properties and start the program:

The program is still running on port 9090.

If there is no value in the specified profile, it is read from the default profile

Suppose I remove the specified port number for Happy, leaving an empty configuration. To prevent the Tomcat default port 8080, change the default configuration file port to 7777 and start the program:

From the log, you can see that the Happy environment was read.

From the port number, you can see that it reads the value in the default configuration.

conclusion

Multiple sets of configuration files, which are often used in real development. Configure different configuration files for different environments, facilitating development, testing, and deployment.