关闭

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

发表于:2015-11-06 11:10

字体: | 上一篇 | 下一篇 | 我要投稿

 作者:pan12jian    来源:51Testing软件测试网采编

  在很多互联网项目中,测试环境和线上环境都是分离的,那么为了方便开发测试,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=convertToNull
  jdbc.username=testuser
  jdbc.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 stub
ResourceBundle res = ResourceBundle.getBundle("db");
String username=res.getString("username");
System.out.println(username);
}
}
  上面配置默认是采用dev属性,若要部署到线上,则在编译时用-Pproduct选线,
  如:mvn compile -Pproduct,mvn package -Pproduct
《2023软件测试行业现状调查报告》独家发布~

关注51Testing

联系我们

快捷面板 站点地图 联系我们 广告服务 关于我们 站长统计 发展历程

法律顾问:上海兰迪律师事务所 项棋律师
版权所有 上海博为峰软件技术股份有限公司 Copyright©51testing.com 2003-2024
投诉及意见反馈:webmaster@51testing.com; 业务联系:service@51testing.com 021-64471599-8017

沪ICP备05003035号

沪公网安备 31010102002173号