20191112 Spring Boot官方文档学习(4.3)

4.3。Profiles

Spring Profiles提供了一种隔离部分应用程序配置并使之仅在某些环境中可用的方法。任何@Component@Configuration@ConfigurationProperties可被标记@Profile,当它被加载时,限制使用。

如果@ConfigurationProperties通过@EnableConfigurationProperties而不是自动扫描来注册bean ,则@Profile需要在@EnableConfigurationProperties指定的@Configuration类上。在@ConfigurationProperties被扫描的情况下,@Profile可以在@ConfigurationProperties类本身上指定。Spring Boot默认使用自动扫描的方式。

使用spring.profiles.active属性指定激活的profiles。

spring.profiles.active=dev,hsqldb

使用以下开关在命令行中指定它:

--spring.profiles.active=dev,hsqldb

4.3.1。添加激活的Profiles

spring.profiles.active属性与其他属性遵循相同的排序规则:最高级别的PropertySource获胜。这意味着您可以在其中指定活动配置文件application.properties,然后使用命令行开关替换它们。

有时,将特定于profiles的属性添加到激活的profiles而不是替换它们很有用。spring.profiles.include属性可用于无条件添加激活的profiles。SpringApplication可以添加profiles(对那些被激活的spring.profiles.active属性)。参见org.springframework.boot.SpringApplication#setAdditionalProfiles

当使用开关运行具有以下属性的应用程序时--spring.profiles.active=prod,proddb和prodmq配置文件也会被激活:

---
my.property: fromyamlfile
---
spring.profiles: prod
spring.profiles.include:
  - proddb
  - prodmq

4.3.2。以编程方式设置Profiles

可以通过方法org.springframework.boot.SpringApplication#setAdditionalProfiles 设置;

也可以通过Spring的org.springframework.core.env.ConfigurableEnvironment接口设置。

4.3.3。特定于Profile的配置文件

application.properties(或application.yml)的特定于Profile的配置文件的变种和通过@ConfigurationProperties引用的文件都被视为文件并加载。

猜你喜欢

转载自www.cnblogs.com/huangwenjie/p/11845865.html