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

问题描述 投票:1回答:1

我想写一个几个域类可以共享的特征。例如,我有两个域类

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默认由所有域实现。

grails gorm traits
1个回答
1
投票

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

import grails.artefact.Enhances

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

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

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

© www.soinside.com 2019 - 2024. All rights reserved.