0

我继承了一些 grails 代码,并试图了解下面create方法的本质。它是 AttributeService 拥有的Attribute属性的某种 grails 关键字构造函数吗?我看不到create方法在哪里被调用。谢谢。

class AttributeService {

    boolean transactional = false

    def uiKey2Attribute = [:]
    def internalName2Attribute = [:]

    def Attribute create(String internalName, String displayName) {
        Attribute attribute = new Attribute();
        attribute.setInternalName(internalName);
        attribute.setUiKey(internalName.replaceAll(' ', '_'))
        attribute.setDisplayName(displayName);
        return attribute;
    }

}
4

1 回答 1

1

这只是服务中的一个公共方法,它返回Attribute应用某些规则的新实例。

搜索“attributeService”以查看它的使用位置,因为 Grails 在他的人工制品(控制器、标签库......)上使用依赖注入。

考虑到控制器应该尽可能轻,只处理请求,服务是操作域类(创建、保存、删除等)的好地方,这可能是 AttributeService 所做的。

这是移植到 Grails 的 Petclinic Spring 示例,也许它会帮助您理解控制器和服务的概念。

编辑
为了给您的探索增添一些刺激,这就是服务类在变得更规范时的样子:

class AttributeService {
    /**
     * This property decides whether the service class
     * is transactional by default or not
     */
    static transactional = false

    /**
     * Grails service class is singleton by default
     * So class level variables maintain state across the requests.
     * Beware of using global variables
     */
    def uiKey2Attribute = [:]
    def internalName2Attribute = [:]

    /**
     * You can either use def or the actual class as the return type
     * Best practice is the provide the signature of method fully typed
     * if you already know what the return type would be.
     * This is self documenting.
     * And would not confuse other developer if you use something like
     *  def create(internalName, displayName) which is valid in Groovy as well.
     */
    Attribute create(String internalName, String displayName) {
        Attribute attribute = new Attribute()
        attribute.setInternalName(internalName)
        attribute.setUiKey(internalName.replaceAll(' ', '_'))
        attribute.setDisplayName(displayName)
        //return is optional
        //last statement in a method is always returned
        attribute
    }
}
于 2013-08-16T19:12:31.473 回答