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