【发布时间】:2012-12-10 12:25:31
【问题描述】:
我发现自己在使用 groovy 编程时避免使用 def 关键字,因为我喜欢使用类型的明确性。我想知道使用类型与使用 def 注入服务有什么含义?我想它对模拟注入的可测试性有潜在的影响。还要别的吗?
我看到the documentation 中提到的两种方法。
人们现在认为最佳做法是什么?
【问题讨论】:
我发现自己在使用 groovy 编程时避免使用 def 关键字,因为我喜欢使用类型的明确性。我想知道使用类型与使用 def 注入服务有什么含义?我想它对模拟注入的可测试性有潜在的影响。还要别的吗?
我看到the documentation 中提到的两种方法。
人们现在认为最佳做法是什么?
【问题讨论】:
当使用显式类型声明时(对于 2.0 之前的 grails),曾经存在重新加载注入其他服务的服务的问题。我在 grails jira 中没有看到任何关于此的最新信息,因此这可能已在更新的版本中得到修复。
【讨论】:
def 是类型名称的替代品。在变量定义中,它用于表示您不关心类型。 Is there any difference between declaring a variable with 'def' and declaring it with a known type?
def num = 1
Integer number = 2
assert num.class == Integer
assert number.class == Integer
我更喜欢使用 def 进行依赖注入,我认为这是 Grails 中最常见的。
【讨论】: