Grails binddata in service

后端 未结 3 1751
清歌不尽
清歌不尽 2021-02-04 20:20

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

TestObject testOb         


        
相关标签:
3条回答
  • 2021-02-04 20:30

    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
        }
    }
    
    0 讨论(0)
  • 2021-02-04 20:47

    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)
    
    0 讨论(0)
  • 2021-02-04 20:49

    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;
    }
    
    0 讨论(0)
提交回复
热议问题