Grails:如何为域 类 编写特征?

Grails: How to write traits for domain classes?

我想写几个领域 类 会共享的特征。例如我有两个域 类 这样的

class Comment{

   String description

   static hasMany = [replies: CommentReply]

   String getFormattedDescription(){
        // ...
         return formattedDescription
   }
}

class CommentReply{
   String description

   Comment comment

   String getFormattedDescription(){
        // ...
         return formattedDescription
   }
}

在这种情况下,Comment 和 CommentReply 都具有相同的函数 getFormattedDescription(),可以将其移动到特征并由两个域实现 类。我怎样才能做到这一点?

如何编写所有域 类 都会实现的特征?例如GormEntity默认被所有域实现。

一种方法是编写特征并用 @Enhances('Domain') 标记。

import grails.artefact.Enhances

@Enhances('Domain')
trait YourTraitName {
    // ...
}

这会将 YourTraitName 添加到所有域 类。

为了使其正常工作,您需要在您的应用程序代码之前配置要在其自己的源集中编译的特征。一种常见的管理方法是在插件中具有特征(它可以是多项目构建的一部分)。