Spring Boot配置特定属性spring.profiles


SpringBoot能使用application- {你的自定义profile名称myProfileName} .properties模式添加任何你指定配置文件到其属性文件。
要加载特定的配置文件属性文件,我们可以使用命令行选项-Dspring.profiles.active = myProfileName。
缺省默认SpringBoot是加载application.properties,无需任何-Dspring.profile.active选项,或使用-Dspring.profiles.active = default来加载。默认属性文件也可以命名为application-default.properties。
默认配置文件application.properties中指定的任何属性将被你指定加载的配置文件中的的属性覆盖。
也可以在application.properties中指定激活配置文件。
spring.profiles.active=prod

比如你有三个配置文件:
src/main/resources/application.properties(默认的)
src/main/resources/application-dev.properties(你指定的dev)
src/main/resources/application-prod.properties(你指定的prod)

如果在application.properties中有:
spring.profiles.active=prod
那么SpringBoot将加载application-prod.properties内容。

如果你在代码中使用配置文件中的变量:

@Component
public class ClientBean {
  @Value("${app.window.width}")
  private int width;
  @Value(
"${app.window.height}")
  private int height;

如果application-prod.properties和application.properties都有app.window.width和app.window.height,那么以prod中配置的值为主。


spring.profile.include属性
在application-prod.properties还可以加入
spring.profiles.include=throttling,db

这是无条件地添加活动配置文件(以逗号分隔)。此属性添加的配置文件不会根据某些条件或命令行开关决定是否添加,而是始终无条件添加它们。

上述配置是就加载了:
src/main/resources/application-throttling.properties
src/main/resources/application-db.properties
这两个配置文件中的内容。