maven项目用filter管理不同环境的配置文件

来源:互联网 发布:圆方家居设计软件2.0 编辑:程序博客网 时间:2024/05/30 05:30

在很多互联网项目中,测试环境和线上环境都是分离的,那么为了方便开发测试,maven项目可以在编译时选取不同的配置文件。配置也比较简单。

1.项目目录结构如下:

2.各个文件内容,

1)修改pom.xml文件,添加如下内容

<profiles><!-- 开发/测试环境,默认激活 --><profile><id>test</id><properties><env>test</env></properties><activation><activeByDefault>true</activeByDefault><!--默认启用的是dev环境配置 --></activation></profile><!-- 生产环境 --><profile><id>product</id><properties><env>product</env></properties></profile></profiles><build><plugins><plugin><artifactId>maven-compiler-plugin</artifactId><version>3.1</version><configuration><source>1.7</source><target>1.7</target></configuration></plugin></plugins><filters> <!-- 指定使用的 filter --><filter>src/main/filters/filter-${env}-env.properties</filter></filters><resources><resource><directory>src/main/resources</directory><filtering>true</filtering></resource></resources></build>


3.filter-test-env.properties内容

jdbc.url=jdbc:mysql://192.168.120.220:3306/testdb?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNulljdbc.username=testuserjdbc.password=123456

4.db.properties内容

url=${jdbc.url}username=${jdbc.username}password=${jdbc.password}

5,java获取属性的代码如下:

package com.jumei.mvntest;import java.io.FileNotFoundException;import java.util.ResourceBundle;public class test {public static void main(String[] args) throws FileNotFoundException {// TODO Auto-generated method stubResourceBundle res = ResourceBundle.getBundle("db");String username=res.getString("username");System.out.println(username);}}

上面配置默认是采用dev属性,若要部署到线上,则在编译时用-Pproduct选线,

如:mvn compile -Pproduct,mvn package -Pproduct


0 0
原创粉丝点击