【问题标题】:Maven profiles equivalent of Gradle相当于 Gradle 的 Maven 配置文件
【发布时间】:2017-04-01 07:05:36
【问题描述】:
我试图在我的 spring boot 项目构建中实现一个简单的场景:包括/排除依赖项以及根据环境打包 war 或 jar。
例如,对于环境 dev 包括 devtools 和 package jar,对于 prod package war 等。
我知道它不再是基于 XML 的配置,我基本上可以在 build.gradle 中编写 if 语句,但有推荐的方法来实现这一点吗?
我可以声明一些常见的依赖项并在单个文件中引用它们而不是创建多个构建文件吗?
是否有根据构建目标环境更改构建配置的最佳实践?
【问题讨论】:
标签:
java
gradle
spring-boot
build.gradle
spring-boot-gradle-plugin
【解决方案1】:
ext {
devDependencies = ['org.foo:dep1:1.0', 'org.foo:dep2:1.0']
prodDependencies = ['org.foo:dep3:1.0', 'org.foo:dep4:1.0']
isProd = System.properties['env'] == 'prod'
isDev = System.properties['env'] == 'dev'
}
apply plugin: 'java'
dependencies {
compile 'org.foo:common:1.0'
if (isProd) {
compile prodDependencies
}
if (isDev) {
compile devDependencies
}
}
if (isDev) tasks.withType(War).all { it.enabled = false }
【解决方案2】:
我的版本(灵感来自Lance Java's answer):
apply plugin: 'war'
ext {
devDependencies = {
compile 'org.foo:dep1:1.0', {
exclude module: 'submodule'
}
runtime 'org.foo:dep2:1.0'
}
prodDependencies = {
compile 'org.foo:dep1:1.1'
}
commonDependencies = {
compileOnly 'javax.servlet:javax.servlet-api:3.0.1'
}
env = findProperty('env') ?: 'dev'
}
dependencies project."${env}Dependencies"
dependencies project.commonDependencies
if (env == 'dev') {
war.enabled = false
}
【解决方案3】:
有时,通过向文件settings.gradle 添加一些代码行来在不同的构建文件之间完全切换也很有用。本方案读取环境变量BUILD_PROFILE,插入buildFileName:
# File: settings.gradle
println "> Processing settings.gradle"
def buildProfile = System.getenv("BUILD_PROFILE")
if(buildProfile != null) {
println "> Build profile: $buildProfile"
rootProject.buildFileName = "build-${buildProfile}.gradle"
}
println "> Build file: $rootProject.buildFileName"
然后你像这样运行 gradle,例如使用build-local.gradle:
$ BUILD_PROFILE="local" gradle compileJava
> Processing settings.gradle
> Build profile: local
> Build file: build-local.gradle
BUILD SUCCESSFUL in 3s
这种方法也适用于 CI/CD 管道,您可能想要添加额外的任务,例如检查质量门或其他您不想在本地执行的耗时的事情。