"Quick to learn springboot" SpringBoot multi-environment configuration file

Foreword

We all know that springboot unloading application.properties configuration profiles (or application.yml). However, if you want to separate different environments (such as the development environment, test environment, the production environment) profile, which how to do it? In fact, SpringBoot support specify a different profile.

SpringBoot Configuration File Format

In Spring Boot multi environment configuration file names need to meet application- {profile} .properties format, wherein {profile} identification corresponding to your environment (not necessarily .properties file, the file may be .yml). The value of the profile, a developer of custom, only at boot time, add the corresponding parameters, springboot will go to read the configuration files. For example, we can define the following format:

application-dev.properties:开发环境 
application-test.properties:测试环境 
application-prod.properties:生产环境 

If you start when you do not specify the configuration file, or specify the configuration file does not have a corresponding entry will be read from the default configuration file. The default configuration file: application.properties (or application.yml)

Start the specified environment

We can specify the environment through spring.profiles.active parameters.

Suppose there are two profiles:

application.properties

server.port=8080

application-happy.properties

server.port=9090

If we do not specify an environment, direct start, will start in 8080:

java -jar springboot-0.0.1-SNAPSHOT.jar

The method starts with the specified environment

Specify the command line to start

You can add -Dspring.profiles.active = Manner specified

For example, specify the happy environment:

java -jar "-Dspring.profiles.active=happy" springboot-0.0.1-SNAPSHOT.jar

The default configuration file specifies

Add in the application.properties

spring.profiles.active=happy

starting program:

Specified in the IDEA

In the run / debug configuration, the environment may be configured as follows:

Application.properties specified in the environment removed, start the program:

The program still starts in the 9090 port.

Specified in the configuration file no value from the default configuration file read

假如我把happy的指定端口号去掉,留下一个空配置。为了防止Tomcat默认端口8080的情况,把默认配置文件的端口改为7777,然后启动程序:

通过日志,可以看到是读取了happy环境。

通过端口号,可以看到其读取了默认配置中的值。

总结

多套配置文件,这在实际开发中是经常用到的。根据不同的环境,配置不同的配置文件,方便开发也方便测试和部署。

Guess you like

Origin www.cnblogs.com/happy4java/p/11206503.html