Spring上的-Drun.profiles和-Dspring.profiles.active有什么区别?

Dhe*_*rik 2 java profile spring maven spring-boot

我试图理解 Spring 和 之间的-Drun.profiles区别-Dspring.profiles.active

SO 中的另一个答案并没有过多解释其中的差异。

在我的测试中,它们都可以用来选择配置文件:

mvn spring-boot:run -Drun.profiles=prod
Run Code Online (Sandbox Code Playgroud)

或者

mvn spring-boot:run -Dspring.profiles.active=prod
Run Code Online (Sandbox Code Playgroud)

那么,有什么区别呢?

Mar*_*nik 5

spring.profiles.active是 Spring Boot 应用程序开箱即用支持的属性之一。它用于在 Spring Boot 应用程序级别指定应运行哪些配置文件。

Spring Boot 支持许多不同的属性,可以在此处找到完整列表。

现在,您不会run.profiles在这些属性中找到,因为它只是 Spring Boot Maven 插件支持的属性(是的,它将它“翻译”为要使用的配置文件列表,因此这些属性可能看起来相似),但重点是,-Drun.profiles只有当您使用 Maven 插件启动 Spring Boot 应用程序时,这才有效。

然而,在生产中,很可能根本不会有 Maven,应用程序将按原样(作为一个大 jar)运行,甚至打包为 Docker 映像或其他东西。因此,对于非 Maven 插件使用,您应该使用spring.profiles.active

最后一点,即使在 Maven 中也--spring.profiles.active可以使用,但它不能开箱即用。您应该像这样传递这个参数:

mvn spring-boot:run -Drun.jvmArguments="-Dspring.profiles.active=production"
Run Code Online (Sandbox Code Playgroud)

请参阅Github 中的此项

希望这能澄清两者之间的差异。