多数项目都会有开发环境、测试环境、生产环境,各个环境配置可能都会不一样,于是在构建时,会涉及到环境配置的切换。来回手工修改配置,效率低下,容易出错。可以配置多个含有不同环境配置的Profile,在构建时指定构建环境,达到多环境下快速灵活构建的目的。

项目结构:

config.properties:

jdbc_driver_class=${jdbc.driver.class}
jdbc_connection_url=${jdbc.connection.url}
jdbc_username=${jdbc.username}
jdbc_password=${jdbc.password}

prop下的dev.properties、test.properties、prod.properties分别对应开发、测试、生产环境的配置。

dev.properties:

jdbc.driver.class=com.mysql.jdbc.Driver
jdbc.connection.url=jdbc:mysql://localhost:3306/mydb
jdbc.username=dev_user
jdbc.password=123456

test.properties:

jdbc.driver.class=com.mysql.jdbc.Driver
jdbc.connection.url=jdbc:mysql://192.168.1.25:3306/mydb
jdbc.username=test_user
jdbc.password=123456

prod.properties:

jdbc.driver.class=com.mysql.jdbc.Driver
jdbc.connection.url=jdbc:mysql://www.nocoffee.com:3306/mydb
jdbc.username=prod_user
jdbc.password=123456

pom.xml:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.coffee</groupId>
  <artifactId>coffee-xw</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>war</packaging>
  
    <profiles>
        <profile>
            <id>dev</id>
            <properties>
                <!-- 自定义属性env,在不同环境有不同的值 -->
                <env>dev</env>
            </properties>
            <activation>
                <!-- 默认激活dev环境的配置 -->
                <activeByDefault>true</activeByDefault>
            </activation>
        </profile>
        
        <profile>
            <id>test</id>
            <properties>
                <env>test</env>
            </properties>
        </profile>
        
        <profile>
            <id>prod</id>
            <properties>
                <env>prod</env>
            </properties>
        </profile>
    </profiles>
    
    <build>
        <!-- 指定filter,根据最终profile下的env属性获取对应的配置文件 -->
        <filters>
            <filter>src/main/prop/${env}.properties</filter>
        </filters>
        
        <!-- 开启资源过滤,让Maven能解析资源文件中的Maven属性 -->
        <resources>
            <resource>
                <directory>src/main/resources</directory>
                <filtering>true</filtering>
            </resource>
        </resources>
    </build>
</project>

构建

构建时,指定参数-P加上profile的id来激活对应的profile。也可以通过指定默认激活的profile。
如上,显示的激活dev环境的profile,执行mvn clean install 时,编译后的config.properties内容为:

jdbc_driver_class=com.mysql.jdbc.Driver
jdbc_connection_url=jdbc:mysql://localhost:3306/mydb
jdbc_username=dev_user
jdbc_password=123456

执行 mvn clean install -Pprod 时,编译后的config.properties内容为:

jdbc_driver_class=com.mysql.jdbc.Driver
jdbc_connection_url=jdbc:mysql://www.nocoffee.com:3306/mydb
jdbc_username=prod_user
jdbc_password=123456
内容来源于网络如有侵权请私信删除
你还没有登录,请先登录注册
  • 还没有人评论,欢迎说说您的想法!