簡體   English   中英

從其他屬性文件替換 application.properties 的值

[英]Replace value of application.properties from other properties file

我的 Spring boot 應用程序中有以下文件應用程序屬性文件。 所有屬性文件都在 src/main/resources 文件夾中Spring boot 版本為 2.1.6

application.properties application-dev.properties application-tst.properties

application.properties app.name={app.name} app.common=通用值
application-dev.properties app.name=我的開發應用
application-tst.properties app.name=我的 tst 應用

Dev 和 tst 是我創建的 Maven 配置文件

 <profiles>
        <profile>
            <id>dev</id>
            <activation>
                <activeByDefault>true</activeByDefault>
            </activation>
            <properties>
                <env>dev</env>
            </properties>
        </profile>

        <profile>
            <id>tst</id>
            <properties>
                <env>tst</env>
            </properties>
        </profile>
    </profiles>

如果我使用 dev profile 構建項目,我應該在我的 application.properties 中得到以下內容

1)mvn -Pdev 全新安裝

application.properties app.name=我的開發應用app.common=通用值

2)mvn -Ptst 全新安裝

application.properties app.name=我的 tst 應用 app.common=Common val

我怎樣才能做到這一點?

您可以像這樣使用環境變量來設置活動配置文件

mvn install -Dspring.profiles.active=dev

或者

mvn install -Dspring.profiles.active=tst

這可能不是推薦的方式,但您可以使用org.apache.maven.plugins.maven-resources-plugin如下。

pom.xml

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-resources-plugin</artifactId>
                <version>3.1.0</version>
            </plugin>
        </plugins>
        <resources>
            <resource>
                <directory>src/main/resources</directory>
                <filtering>true</filtering>
            </resource>
        </resources>
        <filters>
            <filter>src/main/resources/application-${env}.properties</filter>
        </filters>
    </build>

應用程序屬性

app.name=@app.name@
app.common=Common val

應用程序-dev.properties

app.name=My dev app

應用程序-tst.properties

app.name=My tst app

然后, mvn -Pdev clean installmvn -Ptst clean install

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM