除了使用已弃用的bindData
之外,是否可以在服务中使用BindDynamicMethod
?我不能只使用
TestObject testObject = new TestObject()
TestObject testObject.properties = params
或
TestObject testObject = new TestObject(params)
因为我的@BindUsing
类中有TestObject
注释的自定义绑定方法。
答案 0 :(得分:12)
如果您使用的是Grails 3. *,那么服务类可以实现DataBinder
特征并实现bindData()
,如下所示:
import grails.web.databinding.DataBinder
class SampleService implements DataBinder {
def serviceMethod(params) {
Test test = new Test()
bindData(test, params)
test
}
class Test {
String name
Integer age
}
}
这就是我在grails控制台中快速尝试的方法:
grailsApplication.mainContext.getBean('sampleService').serviceMethod(name: 'abc', age: 10)
答案 1 :(得分:4)
在Grails 2.4.4中你可以这样做:
// grails-app/services/demo/HelperService.groovy
package demo
import org.grails.databinding.SimpleMapDataBindingSource
class HelperService {
def grailsWebDataBinder
TestObject getNewTestObject(Map args) {
def obj = new TestObject()
grailsWebDataBinder.bind obj, args as SimpleMapDataBindingSource
obj
}
}
答案 2 :(得分:0)
在2.5中,我发现在辅助服务中模拟Controller API的行为是有效的:
def bindData(def domainClass, def bindingSource, String filter) {
return bindData(domainClass, bindingSource, Collections.EMPTY_MAP, filter)
}
def bindData(def domainClass, def bindingSource, Map includeExclude, String filter) {
DataBindingUtils
.bindObjectToInstance(
domainClass,
bindingSource,
convertToListIfString(includeExclude.get('include')),
convertToListIfString(includeExclude.get('exclude')),
filter);
return domainClass;
}
convertToListIfString是根据控制器方法:
@SuppressWarnings("unchecked")
private List convertToListIfString(Object o) {
if (o instanceof CharSequence) {
List list = new ArrayList();
list.add(o instanceof String ? o : o.toString());
o = list;
}
return (List) o;
}