在上一篇文章中,我们学习了如何在Gradle项目中运行Java应用程序。 具有main
方法的Java源文件是该项目的一部分,我们使用JavaExec
任务来运行Java代码。 我们可以使用相同的JavaExec
任务来运行Groovy脚本文件。
Groovy脚本文件没有显式的main
方法,但是在我们编译脚本文件时添加了它。 脚本文件的名称也是生成的类的名称,因此我们将该名称用于JavaExec
任务的main
属性。 让我们首先创建简单的Groovy脚本文件以显示当前日期。 我们可以使用我们不想使用的日期格式传递一个额外的参数。
// File: src/main/groovy/com/mrhaki/CurrentDate.groovy
package com.mrhaki
// If an argument is passed we assume it is the
// date format we want to use.
// Default format is dd-MM-yyyy.
final String dateFormat = args ? args[0] : 'dd-MM-yyyy'
// Output formatted current date and time.
println "Current date and time: ${new Date().format(dateFormat)}"
我们的Gradle构建文件包含JavaExec
类型的任务runScript
。 我们依赖Gradle附带的Groovy库,因为我们使用localGroovy()
作为编译依赖项。 当然,如果我们要使用组,名称和版本表示法以及有效的存储库,可以将其更改为引用另一个Groovy版本。
// File: build.gradle
apply plugin: 'groovy'
dependencies {
compile localGroovy()
}
task runScript(type: JavaExec) {
description 'Run Groovy script'
// Set main property to name of Groovy script class.
main = 'com.mrhaki.CurrentDate'
// Set classpath for running the Groovy script.
classpath = sourceSets.main.runtimeClasspath
if (project.hasProperty('custom')) {
// Pass command-line argument to script.
args project.getProperty('custom')
}
}
defaultTasks 'runScript'
我们可以在有或没有项目属性custom
情况下运行脚本,然后在输出中看到更改:
$ gradle -q
Current date and time: 29-09-2014
$ gradle -q -Pcustom=yyyyMMdd
Current date and time: 20140929
$ gradle -q -Pcustom=yyyy
Current date and time: 2014
用Gradle 2.1编写的代码。
翻译自: https://www.javacodegeeks.com/2014/10/gradle-goodness-running-groovy-scripts-as-application.html