1. 程式人生 > >java引用pom中定義的變數解決方案

java引用pom中定義的變數解決方案

上一篇文章,是通過properties定義變數,然後pom引入properties檔案,這樣就能在java程式碼中直接引入;也可以使用maven佔位符來解決該問題,具體細節如下:

1.properties檔案中環境變數定義

 

2.pom檔案中對應部署環境引入對應properties檔案

</build>
<profiles><!--部署環境-->
    <profile>
        <id>local</id><!--local環境-->
        <build>
            <resources>
                <resource>
                    <directory>src/main/profiles/local</directory><!--引入properties檔案地址-->
                </resource>
            </resources>
        </build>
        <properties>
            <profile.env>local</profile.env><!--變數,標識環境-->
            <log.root.level>INFO</log.root.level>
            <log.logger.level>DEBUG</log.logger.level>
            <log.console.level>INFO</log.console.level> 
        </properties>
    </profile>

<profile>
        <id>development</id><!--local環境-->
        <build>
            <resources>
                <resource>
                    <directory>src/main/profiles/development</directory><!--引入properties檔案地址-->
                </resource>
            </resources>
        </build>
        <properties>
            <profile.env>development</profile.env><!--變數,標識環境-->
            <log.root.level>INFO</log.root.level>
            <log.logger.level>DEBUG</log.logger.level>
            <log.console.level>INFO</log.console.level> 
        </properties>
    </profile>

<profile>
        <id>preview</id><!--local環境-->
        <build>
            <resources>
                <resource>
                    <directory>src/main/profiles/preview</directory><!--引入properties檔案地址-->
                </resource>
            </resources>
        </build>
        <properties>
            <profile.env>preview</profile.env><!--變數,標識環境-->
            <log.root.level>INFO</log.root.level>
            <log.logger.level>DEBUG</log.logger.level>
            <log.console.level>INFO</log.console.level> 
        </properties>
    </profile>
    <profile>
        <id>product</id><!--生產部署環境-->
        <build>
            <resources>
                <resource>
                    <directory>src/main/profiles/production</directory><!--引入properties檔案地址-->
                </resource>
            </resources>
        </build>
        <properties>
            <profile.env>product</profile.env><!--product-->
            <log.root.level>INFO</log.root.level>
            <log.logger.level>DEBUG</log.logger.level>
            <log.console.level>INFO</log.console.level>
           <!--相關佔位符變數配置,例如:xml中配置為${node.path},則pom進行如下配置-->
           <node.path>main.js</node.path>
        </properties>
    </profile>
</profiles>

3.在java程式碼中使用變數接收引數:

@Value("${profile.env}")//SpringEl表示式
private String env;
4.這樣就可以獲取到對應編譯環境的環境變數。