Maven Profile按環境打包

在日常開發中,我們項目的開發環境和生產環境以及測試環境往往是不同的,比如:數據庫的url等。在項目上生產環境時,就需要修改這些參數,給開發造成不便。 爲了解決該問題,Maven 2.0引入了構建配置文件的概念(build profiles)。

它能幹什麼呢?

假如你的生產環境和開發環境所需環境配置不同,生產環境配置文件是pro.properties,開發環境配置文件是dev.properties,那麼用maven profile , 你可以實現打包開發環境jar包的時候只將dev.properties打包並使用,生產環境打包同理。

在哪裏聲明呢?

它可以在每個項目的pom.xml文件中聲明,也可以在maven的用戶setting.xml下聲明,也可以在maven全局環境下設置setting.xml,詳情如下。

1. Per Project

Defined in the POM itself (pom.xml).

2. Per User

Defined in the Maven-settings (%USER_HOME%/.m2/settings.xml)

3. Global

Defined in the global Maven-settings (${maven.home}/conf/settings.xml)

4. Profile descriptor

不支持3.0,詳情請看: https://cwiki.apache.org/MAVEN/maven-3x-compatibility-notes.html#Maven3.xCompatibilityNotes-profiles.xml

雖然有這麼多define的方式,但是我們一般使用的是第一種defined in the pom,因爲不見得每個項目的生產環境都一模一樣,當然這個也是因個人情況而異。

實戰

1. 項目結構

├── pom.xml
├── src
│   ├── main
│   │   ├── java
│   │   │   └── com
│   │   │       └── fantj
│   │   └── resources
│   │       └── conf
│   │           ├── dev
│   │           │   └── application.properties
│   │           ├── pro
│   │           │   └── application.properties
│   │           └── test
│   │               └── application.properties
│   └── test
│       └── java

2. pom.xml

    <profiles>
        <profile>
            <id>dev</id>
            <properties>
                <profile.env>dev</profile.env>
            </properties>
            <activation>
                <activeByDefault>dev</activeByDefault>
            </activation>
        </profile>
        <profile>
            <id>pro</id>
            <properties>
                <profile.env>pro</profile.env>
            </properties>
        </profile>
        <profile>
            <id>test</id>
            <properties>
                <profile.env>test</profile.env>
            </properties>
        </profile>
    </profiles>

    <build>
        <resources>
            <resource>
                <directory>${basedir}/src/main/resources</directory>
                <excludes>
                    <exclude>conf/**</exclude>
                </excludes>
            </resource>
            <resource>
                <directory>src/main/resources/conf/${profile.env}</directory>
            </resource>
        </resources>
    </build>

3. 三個application.properties

dev/application.properties

env=dev
db.url=192.168.0.166  
db.username=db-dev 
db.password=db-dev

pro/application.properties

env=pro
db.url=47.xxx.xxx.xxx  
db.username=db-pro
db.password=db-pro

test/application.properties

env=test
db.url=127.0.0.1 
db.username=db-test
db.password=db-test

4. 打包

mvn clean install -P pro

可以看到只將pro/application.properties進行了編譯。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章