这是Grails构造函数吗?

时间:2013-08-16 19:00:40

标签: grails

我继承了一些grails代码,并试图了解下面创建方法的性质。它是属性属性的某种grails关键字构造函数,由 AttributeService 拥有?我没有看到在任何地方调用创建方法的位置。感谢。

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;
    }

}

1 个答案:

答案 0 :(得分:1)

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

搜索“attributeService”以查看其使用位置,因为Grails对其人工制品使用依赖注入(controller,taglib ...)。

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

Here is the Petclinic移植到Grails的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
    }
}