Grails binddata in service

£可爱£侵袭症+ 提交于 2020-11-30 07:35:30

问题


Is there a way to utilize bindData in a service other than using the deprecated BindDynamicMethod? I can't just use

TestObject testObject = new TestObject()
TestObject testObject.properties = params

or

TestObject testObject = new TestObject(params)

because I have a custom bind method utilizing the @BindUsing annotation within my TestObject class.


回答1:


In Grails 2.4.4 you can do something like this:

// 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:


If you are using Grails 3.* then the service class can implement DataBinder trait and implement bindData() as shown below example:

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

This is how I quickly tried that in grails console:

grailsApplication.mainContext.getBean('sampleService').serviceMethod(name: 'abc', age: 10)



回答3:


In 2.5, I found that emulating the behaviour of the Controller API in a helper service worked:

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 is as per the controller method:

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


来源:https://stackoverflow.com/questions/32317535/grails-binddata-in-service

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!