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

在很多互联网项目中,测试环境和线上环境都是分离的,那么为了方便开发测试,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


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值