AdSense

網頁

2025/2/19

Spring Boot application.properites取得pom.xml的屬性值

Spring Boot的設定檔application.properties取得pom.xml<properties>內的屬性值的方式如下。


設定

Spring Boot專案必須使用spring-boot-starter-parent依賴。

或必須在pom.xml中的<build>下設定resource filtering,用意是在build過程中將src/main/resources目錄下的配置文件中的佔位符@...@替代成參照的值。

pom.xml

<resources>
    <resource>
        <directory>src/main/resources</directory>
        <filtering>true</filtering>
    </resource>
</resources>

最後在pom.xml中的<plugins>下設定maven-resources-plugin<delimiter>@,代表要過濾資源文件的佔位符始末@...@

pom.xml

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-resources-plugin</artifactId>
    <version>2.7</version>
    <configuration>
        <delimiters>
            <delimiter>@</delimiter>
        </delimiters>
        <useDefaultDelimiters>false</useDefaultDelimiters>
    </configuration>
</plugin>

設定好重新執行maven build。


使用

例如pom.xml有以下properties。

pom.xml

<properties>
    <java.version>1.8</java.version>
    <app.tmp.dir>/tmp</app.tmp.dir>
</properties>

則在/resources/application.properties中可以使用@...@取得pom.xml的properties值。

application.properties

app.java.version=@java.version@
app.tmp.dir=@app.tmp.dir@

測試

在Spring Boot應用程式取得properties,可看到值為來自pom.xml的properties值。

package com.abc.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.core.env.Environment;

@SpringBootApplication
public class DemoApplication {

    public static void main(String[] args) {
        ApplicationContext ctx = SpringApplication.run(DemoApplication.class, args);
        Environment env = ctx.getEnvironment();
        System.out.println(env.getProperty("app.java.version")); // 11.0.23 (This is system's java.version value)
        System.out.println(env.getProperty("app.tmp.dir")); // /tmp
    }

}


沒有留言:

AdSense