spring boot多环境情况和属性加载顺序

1、多环境配置

有多个环境的配置文件

 在application,yml配置:

 在pom.xml里面配置:

<profiles>
   <profile>
      <id>dev</id>
      <activation>
         <activeByDefault>true</activeByDefault>
      </activation>
      <properties>
         <profile.env>dev</profile.env>
      </properties>
   </profile>
   <profile>
      <id>test</id>
      <properties>
         <profile.env>test</profile.env>
      </properties>
   </profile>
   <profile>
      <id>product</id>
      <properties>
         <profile.env>product</profile.env>
      </properties>
   </profile>
</profiles>

在build标签里面指定扫描资源范围

<build>
   <plugins>
      <plugin>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-maven-plugin</artifactId>
      </plugin>
      <!--资源引用插件-->
      <plugin>
         <groupId>org.apache.maven.plugins</groupId>
         <artifactId>maven-resources-plugin</artifactId>
         <version>3.0.2</version>
         <configuration>
            <encoding>utf-8</encoding>
            <useDefaultDelimiters>true</useDefaultDelimiters>
         </configuration>
      </plugin>
   </plugins>
</build>

2、加载顺序

启动jar时,可以指定端口:java -jar xxx.jar --server.port=8090
java -jar xxx.jar --spring.profiles.active=test
随机数:

Spring Boot的属性加载顺序,由优先级高到优先级低:
在命令行中传入的参数;
SPRING_APPLICATION_JSON中的属性,SPRING_APPLICATION_JSON是以JSON格式配置在系统环境变量中的内容;
java:comp/env中的JNDI属性;
Java的系统属性,可以通过System.getProperties()获得的内容;
操作系统的环境变量;
通过random.*配置的随机属性;
位于当前应用Jar包之外,针对不同{profile}环境的配置文件内容,例如application-{profile}.properties或者yaml定义的配置文件;
位于当前应用Jar包之内,针对不同{profile}环境的配置文件内容,例如application-{profile}.properties或是yaml定义的配置文件;
位于当前应用Jar包之外的application.properties和yaml配置内容;
位于当前应用Jar包之内的application.properties和yaml配置内容;
在@Configuration注解修改类中,通过@PropertySource注解定义的属性;
应用默认属性,使用SpringApplication.setDefaultProperties定义的内容。

原文地址:https://www.cnblogs.com/longyao/p/11719949.html