Binding real number values to Grails domain attributes (values sent by Dojo widgets)

陌路散爱 提交于 2019-11-30 22:24:04

This issue is fixed in Grails 2.4+

I had similar issue with Long and Integer converter with Grails 2.3.8. Grails is using LocaleAwareNumberConverter which converts string like "123abc" to "123". So I defined my own converter and override the bean definition in resources.groovy

beans = {
    "defaultGrailsjava.lang.LongConverter"(LongValueConverter)
    "defaultGrailsjava.lang.IntegerConverter"(IntegerValueConverter) 
}

class LongValueConverter implements ValueConverter {


    public LongValueConverter() {
    }

    boolean canConvert(value) {
        value instanceof String
    }

    def convert(value) {
        return value?.toLong()
    }

    Class<?> getTargetType() {
        return Long.class
    }
}
sola

I have finally found the solution.

The primary problem was that, the naming of the converter beans was wrong. The two converters dealing with double/Double must be called the following (in the applicationContext):

  • "defaultGrailsdoubleConverter" (for double)
  • "defaultGrailsjava.lang.DoubleConverter" (for Double)

This is slightly confusing since "defaultDateConverter" is named in a much more simple way and I thought the double converter naming will be consistent with that.

Secondary problem is that if you want to override these from a plugin (as opposed to the application project), then you must do the registration from YourGrailsPlugin.doWithSpring() since resources.groovy will not be packaged with the plugin. If you want to do the override from the application project itself, then placing them in resources.groovy is fine.

You may also want to ensure that this registration happens AFTER the DataBinding plugin has been initialized, otherwise your plugin may be initialized first and the DataBinding plugin simply overwrites your converter registration with the defaults. This may be done by announcing a soft dependency on the DataBinding plugin from YourGrailsPlugin.groovy:

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