背景
项目构建的时候,需要根据不同的场景来改变项目中的属性资源,最为常见的莫过于数据库连接配置了,试想有生产环境、测试缓存、发布环境等,需要为不同的场景下来动态的改变数据库的连接配置。而使用maven就可以帮我们解决这些问题。下面就来分享一下maven中的profile和filtering的属性。
为了便于测试一下功能,需要搭建maven的web项目,具体配置请详见如何用maven创建web项目
filtering功能
主要用来替换项目中的资源文件(*.xml、*.properties)当中的 ...,比如 . . . , 比 如 {...},比如{db.url},那么如果配置了db.url=aaa的话,在项目编译的时候,就会自动的把{db.url}替换为aaa,下面以实例来讲解一下
采取参照博客中创建完maven的web项目后,会看到src/main/sources的目录,在此目录下面创建个“test.properties”,里面随便来上一行,例如Hello {db.url}替换为aaa,下面以实例来讲解一下
采取参照博客中创建完maven的web项目后,会看到src/main/sources的目录,在此目录下面创建个“test.properties”,里面随便来上一行,例如Hello {db.url}替换为aaa,下面以实例来讲解一下
采取参照博客中创建完maven的web项目后,会看到src/main/sources的目录,在此目录下面创建个“test.properties”,里面随便来上一行,例如Hello {user.name},好了,接下来修改我们的pom文件,来启动filtering功能
- 4.0.0
- testwebProject
- com.test.web.test
- 0.0.1-SNAPSHOT
- war
- src/main/resources
- **/*.xsd
- **/*.properties
- true
- maven-war-plugin
- 2.5
4.0.0
testwebProject
com.test.web.test
0.0.1-SNAPSHOT
war
src/main/resources
**/*.xsd
**/*.properties
true
maven-war-plugin
2.5
然后编译我们的maven项目
$mvn clean compile -Duser.name=tom
编译完后,查看输出文件 target/classes/test.properties 的内容,可见原先的 “Hello {user.name}” 已经变成 “Hello Tom”。
上面如果麻烦的话,也可以把filtering用到的变量写在项目得属性段里面,如下面的方式
- Lucky
- 50
Lucky
50
进行编译,$mvn clean compile,在此查看的话,就会看到属性被替换的效果
当然了,如果属性比较多的话,那么此时可以把属性单独抽取出来一个*.properties文件来保存,例如我们在pom.xml的同级目录下面创建一个project.properties,里面指明我们的内容
user.name=Lucky
紧接着在修改我们的pom文件,如下
- 4.0.0
- testwebProject
- com.test.web.test
- 0.0.1-SNAPSHOT
- war
- src/main/resources
- **/*.xsd
- **/*.properties
- true
- project.properties
- maven-war-plugin
- 2.5
4.0.0
testwebProject
com.test.web.test
0.0.1-SNAPSHOT
war
src/main/resources
**/*.xsd
**/*.properties
true
project.properties
maven-war-plugin
2.5
再次执行编译命令的话,就会看到效果
profile功能
允许在项目文件(pom.xml)里面定义若干个profile段,然后在编译时选择其中的一个用于覆盖项目文件原先的定义。接着上一个例子,如果我们需要为开发环境和生产环境定义不同的 user.name 属性值,则我们在项目目录里创建两个属性文件分别是pre.properties和dev.properties,然后再每个文件里分别写入user.name=lucky和user.name=wangwang,然后在此修改我们的pom文件,修改后如下所示
- 4.0.0
- testwebProject
- com.test.web.test
- 0.0.1-SNAPSHOT
- war
- src/main/resources
- **/*.xsd
- **/*.properties
- true
- dev
- true
- pre.properties
- pre
- dev.properties
- maven-war-plugin
- 2.5
4.0.0
testwebProject
com.test.web.test
0.0.1-SNAPSHOT
war
src/main/resources
**/*.xsd
**/*.properties
true
dev
true
pre.properties
pre
dev.properties
maven-war-plugin
2.5