将 Maven 依赖项迁移到 gradle

Migrate maven dependencies to gradle

我从软件测试开始 - 使用 Cucumber,Java,gradle。 我试着通过这本书来学习 "The Cucumber for Java Book"

但我尝试使用 gradle 而不是 maven...但是现在我遇到了一些问题... 我坚持第 149 页。我必须给出依赖关系:

<dependency>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-webapp</artifactId>
<version>${jetty.version}</version>
</dependency>

我试着"translate"这个到gradle

dependencies {
     testCompile group: 'junit', name: 'junit', version: '4.12'
     testCompile 'io.cucumber:cucumber-java:2.4.0'
     testCompile 'io.cucumber:cucumber-junit:2.4.0'
     testCompile group: 'info.cukes', name: 'cucumber-picocontainer', version: '1.2.5'
     compile group: 'org.eclipse.jetty', name: 'jetty-webapp', version: '9.4.12.v20180830'
}

这样对吗? 编译组:'org.eclipse.jetty',名称:'jetty-webapp',版本:'9.4.12.v20180830'

之后我必须 运行:

mvn exec:java -Dexec.mainClass="nicebank.AtmServer"

但是我如何用 gradle 做到这一点?

希望有人能帮助我:)

正如我在评论中所说,对 jetty-webapp 的依赖似乎没问题,但你应该使用 implementation 而不是 compilecompile 已被弃用,请参阅 Java dependency configurations):

implementation group: 'org.eclipse.jetty', name: 'jetty-webapp', version: '9.4.12.v20180830'

implementation "org.eclipse.jetty:jetty-webapp:9.4.12.v20180830"

对于 Gradle 中 "maven exec:java" 的等效项,您可以使用 Gradle JavaExec task type:尝试在您的构建中定义一个任务,如下所示:

task runApp(type: JavaExec) {
    classpath = sourceSets.main.runtimeClasspath

    main = 'nicebank.AtmServer'

}

(未测试,您可能需要调整它),并且 运行 与

gradle runApp

您也可以使用 Gretty 插件到 运行 您的 Web 应用程序(在这种情况下无需定义您自己的 JavaExec 任务),如文档所述 here and here :

plugins{
    // your existing plugins   
    id "org.gretty" version "2.2.0"
}

然后您可以 运行 应用程序:

gradle appRun

你的依赖看起来不错。请注意:考虑使用 implementation 而不是 compile,因为它可以提高性能。了解 compile 弃用 here

您还可以将您的属性放入 gradle.properties 文件并在构建脚本中引用它们:

gradle.properties:

jettyVersion=9.4.12.v20180830

build.gradle:

implementation group: 'org.eclipse.jetty', name: 'jetty-webapp', version: jettyVersion

Jetty 团队也发布了 BOMs: — org.eclipse.jetty:jetty-bom:9.4.12.v20180830 in your case. If you use multiple projects of the same version you can import the BOM 并完全跳过版本:

dependencies {
    implementation 'org.eclipse.jetty:jetty-bom:9.4.12.v20180830'
    implementation 'org.eclipse.jetty:jetty-webapp'
    implementation 'org.eclipse.jetty:jetty-runner'
}

至于"exec"任务:如果你的项目中只有一个主要class,比如nicebank.AtmServer,考虑使用Gradle的Application Plugin:

plugins {
    id 'application'
}

mainClassName = 'nicebank.AtmServer'

这样您就不需要手动创建 "exec" 任务,您将从插件中获得一个 (run)。作为奖励,您将获得两个 "distribution" 任务,它们将与您的应用一起创建一个可供分发的存档:distZipdistTar.