我继承了一些 grails 代码,并试图了解 的性质。创建 下面的方法是。它是由 拥有的 Attribute 属性的某种 grails 关键字构造函数吗?属性服务 ?我看不到 的位置创建 方法在任何地方被调用。谢谢。
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;
}
}
最佳答案
这只是服务中的一个公共(public)方法,它返回 Attribute
的新实例。应用一些规则。
搜索“attributeService”以查看它的使用位置,因为 Grails 在他的人工制品( Controller 、标签库...)上使用依赖注入(inject)。
考虑到 Controller 应该尽可能轻,只处理请求,服务是操作域类(创建、保存、删除等)的好地方,这可能是 AttributeService 所做的。
Here is the Petclinic移植到 Grails 上的 Spring 示例,也许它会帮助您理解 Controller 和服务的概念。
编辑
为了给您的探索增添一些刺激,这就是服务类在变得 groovier 时的样子:
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
}
}
关于grails - 这是一个 Grails 构造函数吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18280335/