Gradle的好处:将Groovy脚本作为应用程序运行

在上一篇文章中,我们学习了如何在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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值