这只是服务中的一个公共方法,它返回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
}
}