Maven的档案相当于Gradle

Meh*_*bas 18 java gradle build.gradle spring-boot spring-boot-gradle-plugin

我正在尝试在我的spring boot项目构建中实现一个简单的场景:包括/排除依赖项和打包war或jar,具体取决于环境.

因此,例如,对于环境dev包括devtools和包装罐,prod包装战争等.

我知道它不再是基于XML的配置了,我基本上可以在build.gradle中编写if语句,但有没有推荐的实现方法?

我可以声明一些常见的依赖项并在单个文件中引用它们而不是创建多个构建文件吗?

是否有基于构建目标环境更改构建配置的最佳实践?

lan*_*ava 21

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 }
Run Code Online (Sandbox Code Playgroud)


Vya*_*ets 6

我的版本(受Lance Java的回答启发):

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
}
Run Code Online (Sandbox Code Playgroud)


IPP*_*eek 5

有时,通过向文件添加一些代码行来完全切换不同的构建文件也很有用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"
Run Code Online (Sandbox Code Playgroud)

然后你像这样运行 gradle ,例如使用build-local.gradle

$ BUILD_PROFILE="local" gradle compileJava
> Processing settings.gradle
> Build profile: local
> Build file: build-local.gradle

BUILD SUCCESSFUL in 3s
Run Code Online (Sandbox Code Playgroud)

此方法也适用于 CI/CD 管道,您可能希望在其中添加额外的任务,例如检查质量门或您不想在本地执行的其他耗时的事情。