简体   繁体   中英

Replace value of application.properties from other properties file

I have below file application properties file in my Spring boot application. All properties file are in src/main/resources folder Spring boot version is 2.1.6

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

application.properties app.name={app.name} app.common=Common val
application-dev.properties app.name=My dev app
application-tst.properties app.name=My tst app

Dev and tst are maven profile i have created

 <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>

If i am building the project with dev profile ,i shouuld get the following in my application.properties

1)mvn -Pdev clean install

application.properties app.name=My dev app app.common=Common val

2)mvn -Ptst clean install

application.properties app.name=My tst app app.common=Common val

How can i achieve this ?

You can use the environment variable to set the active profile like this

mvn install -Dspring.profiles.active=dev

or

mvn install -Dspring.profiles.active=tst

This is probably not the recommended way, but you can use org.apache.maven.plugins.maven-resources-plugin as below.

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>

application.properties

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

application-dev.properties

app.name=My dev app

application-tst.properties

app.name=My tst app

and then, mvn -Pdev clean install or mvn -Ptst clean install

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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