首页 > 解决方案 > 使用 Gradle 的弹簧配置文件

问题描述

我正在运行一个包含三个不同属性文件(application.properties、application-prod.properties、application-uat.properties)的 spring boot 项目。我使用的是 Maven,如果我没有指定任何参数,它将选择默认值属性文件,即 application.properties。这是相关文件的外观。

应用程序属性

#Set active profile
spring.profiles.active=@activatedProperties@
    
#MongoDB configuration
spring.data.mongodb.host=${MONGODB_HOST:localhost}
spring.data.mongodb.port=${MONGODB_PORT:27017}
spring.data.mongodb.database=database
spring.data.mongodb.username=username
spring.data.mongodb.password=password

pom.xml

<profiles>
    <profile>
        <id>UAT</id>
        <properties>
            <activatedProperties>uat</activatedProperties>
        </properties>
    </profile>
    <profile>
        <id>PROD</id>
        <properties>
            <activatedProperties>prod</activatedProperties>
        </properties>
    </profile>
</profiles>

如何使用 Gradle 实现相同的目标?如果我没有指定任何争论,我如何让 Gradle 选择默认值(application.properties)?

标签: javaspring-bootgradle

解决方案


我认为此链接对您有用...

https://docs.gradle.org/current/userguide/migrating_from_maven.html#migmvn:profiles_and_properties

样本:

if (!hasProperty('buildProfile')) ext.buildProfile = 'default'  

apply from: "profile-${buildProfile}.gradle"  

task greeting {
    doLast {
        println message  
    }
}

#profile-default.gradle
ext.message = 'foobar' 
 
#profile-test.gradle
ext.message = 'testing 1 2 3'  

#profile-prod.gradle
ext.message = 'Hello, world!'  

此链接也很有用:

https://www.baeldung.com/spring-profiles


推荐阅读