SPRINGBOOT激活不同环境Profiles

SPRING Profiles 提供一种方式隔离应用中某些环境可用的配置文件,任何被 @Component 或者 @Configuration 都可以设置 @Profile 限制加载。

@Configuration
@Profile("production")
public class ProductionConfiguration {

	// ...

}

你可以使用一个spring.profiles.active属性来指定哪个配置生效。你可以在properties 和 yaml 中指定该属性,例如,可以将它包含到你的application.properties中:

spring.profiles.active=dev,hsqldb

或者使用命令行开关:

--spring.profiles.active=dev,hsqldb
添加激活的profiles

spring.profiles.active属性和其他属性一样都遵循相同的排列规则,最高的PropertySource被使用。也就是说,你可以在 application.properties中指定生效的配置,然后使用命令行开关替换它们。

有时,将特定的配置属性添加到生效的配置中而不是替换它们是有用的。spring.profiles.include属性可以用来无条件的添加 生效的配置。 示例:当一个应用使用下面的属性,并用 --spring.profiles.active=prod 开关运行,那proddb和prodmq配置也会生效:

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

注:spring.profiles属性可以定义到一个YAML文档中,用于决定什么时候该文档被包含进配置中。

以编程的方式添加激活profiles

在应用运行前,你可以通过调用SpringApplication.setAdditionalProfiles(…)方法,以编程的方式设置生效的配置。使用 Spring的ConfigurableEnvironment接口激动配置也是可行的。

#ConfigurableEnvironment
void	setActiveProfiles(String... profiles)
设置激活的profiles
void    addActiveProfile(String profile)
添加多个profile在当前激活的profile中
void	setDefaultProfiles(String... profiles)
如果没有通过setActiveProfiles指定激活的profile,则使用该方法设置的profile。
Map<String,Object>	getSystemEnvironment()
如果当前的SecurityManager允许,则返回System.getenv()的值,否则返回一个map实现,该实现将尝试使用对System.getenv(String)的调用来访问各个键。
Map<String,Object>	getSystemProperties()
如果当前的SecurityManager允许,则返回System.getProperties()的值,否则返回一个map实现,该实现将尝试使用对System.getProperty(String)的调用来访问各个键。

评论

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×