简体   繁体   English

在 spring 中加载环境特定的属性文件

[英]Loading environment specific properties file in spring

I am working on a spring-boot application, I need your assistance on below scenario.我正在开发一个 spring-boot 应用程序,我需要您在以下情况下的帮助。

I have properties files for each environment something like application-dev.properties, application-prod.properties etc. Is there way that my application can load environment specific properties file by using spring @Profile annotation.我有每个环境的属性文件,例如 application-dev.properties、application-prod.properties 等。我的应用程序是否可以通过使用 spring @Profile 注释来加载特定于环境的属性文件。

Please help.请帮忙。

You don't need to use @Profiles annotation at all.您根本不需要使用@Profiles注释。 Just use只需使用

@ConfigurationProperties(locations = "classpath:myapp-${environment.type}.properties")

and define environment type via system property.并通过系统属性定义环境类型。 Eg via command line -Denvironment.type=dev .例如通过命令行-Denvironment.type=dev

@Profile is not for loading environment specific properties file. @Profile 不适用于加载特定于环境的属性文件。 It is for specifying profile of a bean.它用于指定 bean 的配置文件。 For example,例如,

@Profile("dev")
@Component
class Foo {

}

It means the bean of Foo is only available when the active profiles include dev .这意味着Foo的 bean 仅在活动配置文件包含dev时可用。 Or the opposite @Profile("!dev") , which means the bean is available when dev is not an active profile.或者相反的@Profile("!dev") ,这意味着当dev不是活动配置文件时,bean 可用。

So for loading environment specific properties file, since it is spring-boot , you can just specify the active profiles.所以对于加载环境特定的属性文件,因为它是spring-boot ,你可以只指定活动配置文件。 There are several ways to specify the active profiles.有几种方法可以指定活动配置文件。

  • Environment variable: SPRING_PROFILES_ACTIVE=dev,prod环境变量: SPRING_PROFILES_ACTIVE=dev,prod
  • command line argument: java -jar app.jar --spring.profiles.active=dev,prod命令行参数: java -jar app.jar --spring.profiles.active=dev,prod
  • Programmatically: SpringApplicationBuilder(...).properties("spring.profiles.active=dev,prod).run(...)以编程方式: SpringApplicationBuilder(...).properties("spring.profiles.active=dev,prod).run(...)
  • Default application.properties or yaml: spring.profiles.active:dev, prod默认 application.properties 或 yaml: spring.profiles.active:dev, prod

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM