Gradle ext 和 def的区别

这篇博客探讨了在Gradle中使用ext和def声明变量的区别。ext用于在项目属性中添加新的属性,方便后续访问,而def则创建的是局部变量,仅在当前作用域内有效。理解这两者的差异对于优化Gradle脚本的组织和可维护性至关重要。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、区别

不太明白gradle中ext和def的区别,stackoverflow【1】中有一段话解释了他们取得区别:

What is the difference between using ext.varname and def varname. E.g. the following code seems to work the same:

使用ext.varname和使用def varname有什么区别呢,他们的作用似乎是一样的。

task copyLicenses {
    def outDir = project.buildDir.absolutePath + '/reports/license/'

    doLast {
        copy {
            from 'licenses'
            into outDir
            include '*'
        }

seems to work exactly the same as

task copyLicenses {
    ext.outDir = project.buildDir.absolutePath + '/reports/license/'

    doLast {
        copy {
            from 'licenses'
            into outDir
            include '*'
        }

Keyword def comes from Groovy and means that variable has local scope.
Using ext.outDir means that you add property outDir to ExtraPropertiesExtension, think of it like project has a map of properties with name ext, and you put your property in this map for later access.

关键字def来自于Groovy,定义了一个local scope的变量。而ext.outDir是新加了一个property:outDir。可以想像成project有一个properties的map,这个map里面有一个键值ext,你把你的property放到这个map里面以便之后引用。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

互联网小熊猫

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值